由于L中的词长度都一样,大大方便了我们每次的循环判断。 思路就是先记录L中有那些词组,以及个字出现的次数。 之后从S头部开始每一个位置判断是否包含L中的全部词组。 如果出现不包含或是多包含就跳出,从下个位置重新开始判断。
这里使用HashMap记录键值对,方便更新。
public class Solution {
public ArrayList<Integer> findSubstring(String S, String[] L) {
ArrayList<Integer> res = new ArrayList<Integer>();
if( S==null || L==null || L.length==0 )
{
return res;
}
HashMap<String,Integer> words = new HashMap<String,Integer>();
for( int i=0;i<L.length;i++ )
{
if( words.containsKey(L[i]) )
{
int tmp = words.get(L[i]);
words.put(L[i],tmp+1);
}
else
{
words.put(L[i],1);
}
}
int wLen = L[0].length();
for( int i=0;i<=(S.length()-L.length*wLen);i++ )
{
HashMap<String,Integer> temp = new HashMap<String,Integer>(words);
int count=L.length;
int st=0;
while(st<count)
{
String str = S.substring(i+st*wLen,i+st*wLen+wLen);
if( !temp.containsKey(str) )
{
break;
}
int num = temp.get(str);
if( num<=0 )
{
break;
}
temp.put(str,num-1);
st++;
}
if( st==count )
{
res.add(i);
}
}
return res;
}
}
本文介绍了一种高效的字符串匹配算法,该算法能够快速地在目标字符串中找到由一系列等长子串组成的序列。通过使用HashMap记录子串及其出现次数,算法能够在O(n)的时间复杂度内完成搜索任务。

被折叠的 条评论
为什么被折叠?



