1

In JavaScript, I need some data structure that can hold strings, and has a fast way to search if a string exists in it, and to insert a string in it.

I was planning to use an array, but I am currently using a dictionary where the key is the string and the value is just 'true' even through I don't use it.

I went with dictionary because I would think it would be something like an AVL tree, where the insert, delete and add are all O(log(n)) time. And the array would have an insert, delete, and search of O(n) time.

Is this right, or is there a better way?

Thanks

4

3 回答 3

2

使用一个对象。

添加字符串:

obj[string] = true;

检查字符串是否存在:

obj.hasOwnProperty(string);
// or simply
obj[string]
于 2013-07-08T18:49:13.083 回答
1

如果使用数组。

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

这应该足够快,它在JS图书馆里。

编辑:

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

于 2013-07-08T18:42:19.150 回答
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"); else console.log("字符串 2 不存在");

if (stringStore['sample-string-3'] ) console.log("string 3 存在"); else console.log("string3 不存在");

于 2013-07-10T14:25:53.003 回答