【问题标题】:how to determine subkey exist in containers.Map in Matlab如何确定子键存在于containers.Map中的Matlab
【发布时间】:2017-11-12 08:21:02
【问题描述】:

我有一个带有字符数组键的 container.Map。例如:

keySet =   {'1 2 4 5', '1 3 45', '1 2', '4 5'};
valueSet = [1, 2, 3, 4];
mapObj = containers.Map(keySet,valueSet)

如果我使用,

isKey(mapObj,'1 2') 

result = 1。我也需要使用子键。意味着我需要确定键中是否存在子键。例如 isSubKey(mapObj,'1 2 5') 结果为 1,因为 '1 2 5' 是 '1 2 4 5' 的子字符串。有没有类似 isSubKey 的方式?

注意:isSubKey(mapObj,'1 2 4 5') 也是 1。

【问题讨论】:

  • 子字符串是什么意思?仅供参考,'1 2 5' 不是'1 2 4 5' 的子字符串(请参阅substring definition)。实际上,'1 2 5'subsequence'1 2 4 5'。那么,您要查找什么 - 子字符串或子序列?
  • 是的,我想找到子序列。我需要像 isKey 这样的快速方法。

标签: matlab dictionary key containers hashtable


【解决方案1】:

您可以使用函数keys 来获取`keys 的列表。

然后您可以使用函数strsplitsub_key 拆分为charcellarray

对 `container 的 keys 执行相同操作。

然后,在三个嵌套的for loops 中,您将sub_key 的令牌与container 键的令牌进行比较。

一个可能的实现可能是:

keySet =   {'1 2 4 5', '1 3 45', '1 2', '4 5'};
valueSet = [1, 2, 3, 4];
mapObj = containers.Map(keySet,valueSet)

% Get the Keys
key_list=keys(mapObj)
% Define the sub_key to be searched
sub_key='1 2'
% Split the sub_key in an cellarray of char
sub_key_c=strsplit(sub_key)
% Initialize counters
idx_f=0
n_of_match=0
cnt=0
found=[]
% Loop over the Container keys
for i=1:length(key_list)
   % Split the current key in an cellarray of char
   key_cell=strsplit(char(key_list(i)))
   % If the lenght of the searched sub_key is greater than the current
   % container key it can not a sub_key
   if(length(key_cell) < length(sub_key_c))
      continue
   end
   idx_f=0
   % Loop over the elements of the sub_key
   for j=1:length(sub_key_c)
      % Loop over the elements of the current key
      for k=1:length(key_cell)
         sub_key_c(j)
         key_cell(k)
         % If a match is found, increment the match counter and go to the
         % next sub_key element
         if(strcmp(sub_key_c(j),key_cell(k)))
            if(idx_f ~= k)
               n_of_match=n_of_match+1
               idx_f=k
               break
            end
         end
      end
   end
   % If the number of matches is equal to the length of the sub_key, the
   % sub_key is actually a sub_key
   if(n_of_match == length(sub_key_c))
      cnt=cnt+1;
      found(cnt)=i
      n_of_match=0
   end
   n_of_match=0
end
% Display the results
if(~isempty(found))
   disp(['The sub_key ' sub_key ' has been found in:'])
   for i=1:length(found)
      key_list(found(i))
   end
else
   disp(['The sub_key ' sub_key ' has not been found'])
end

一些测试:

sub_key='1 2'
The sub_key 1 2 has been found in:
ans = 
    '1 2'
ans = 
    '1 2 4 5'


sub_key='5 4'
The sub_key 5 4 has been found in:
ans = 
    '1 2 4 5'
ans = 
    '4 5'


sub_key='1 1'
The sub_key 1 1 has not been found

【讨论】:

  • 谢谢,但是这个解决方案对我不好。这是时间消耗。我需要一个快速的解决方案。我需要 Hashtable 只是为了速度和需要像 isKey 这样的快速解决方案,因为我的数据太大了。
猜你喜欢
  • 1970-01-01
  • 2016-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-16
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
相关资源
最近更新 更多