什么是检查javascript中字符串集合中是否存在字符串的最快方法?

时间:2013-07-08 18:37:39

标签: javascript arrays dictionary complexity-theory

在JavaScript中,我需要一些可以保存字符串的数据结构,并且可以快速搜索字符串是否存在,并在其中插入字符串。

我打算使用一个数组,但我目前正在使用一个字典,其中键是字符串,即使我不使用它,值也只是'true'。

我选择了词典,因为我认为它类似于AVL树,其中插入,删除和添加都是O(log(n))时间。并且数组将插入,删除和搜索O(n)时间。

这是正确的,还是有更好的方法?

由于

3 个答案:

答案 0 :(得分:2)

使用对象。

添加字符串:

obj[string] = true;

检查字符串是否存在:

obj.hasOwnProperty(string);
// or simply
obj[string]

答案 1 :(得分:1)

如果使用数组。

您可以使用 indexOf() 查找排名。 splice() 将字符串插入数组对象。此外,如果位置无关紧要,请使用push()

这应该足够快,它在JS库中。

编辑:

indexOf()splice()都是线性的。

答案 2 :(得分:0)

var stringStore = {};

stringStore ['sample-string-1'] ='sample-string-1';

stringStore ['sample-string-2'] ='sample-string-2';

if(stringStore ['sample-string-2'])   console.log(“string 2 exists”); 其他   console.log(“字符串2不存在”);

if(stringStore ['sample-string-3'])   console.log(“string 3 exists”); 其他   console.log(“string3不存在”);

相关问题