具有线性时间查找的字符串数组

时间:2012-01-24 20:04:31

标签: string matlab data-structures

我在Matlab中进行字符串处理,我通常使用单元格数组在文本中存储单个单词

示例:

a = {'this', 'is', 'an', 'array', 'of', 'strings'}

为了在这个数组中搜索'of'这个词,我循环遍历数组,并根据我的单词检查每个单独的元素。这种方法不能扩展,因为如果我得到一个大型数据集,我的数组将会变大并且循环遍历元素是不明智的。我想知道是否有更聪明的方法,也许是Matlab中更好的原生数据结构,可以帮助我更快地运行它?

1 个答案:

答案 0 :(得分:3)

map container是一种选择。我不知道您打算做什么特定类型的字符串处理,但这里有一个示例,说明如何将每个字符串存储为与单元数组中该字的索引位置向量相关联的键:

a = {'this', 'is', 'an', 'array', 'of', 'strings', 'this', 'is'};

strMap = containers.Map();  %# Create container
for index = 1:numel(a)      %# Loop over words to add
    word = a{index};
    if strMap.isKey(word)
        strMap(word) = [strMap(word) index];  %# Add to an existing key
    else
        strMap(word) = index;  %# Make a new key
    end
end

然后,您可以获得单词的索引位置:

>> indices = strMap('this')

indices =

     1     7    %# Cells 1 and 7 contain 'this'

或检查单元格数组中是否存在单词(即,如果它是键):

>> strMap.isKey('and')

ans =

     0    %# 'and' is not present in the cell array