作者:disappearedgod
时间:2014-10-4
题目
Substring with Concatenation of All Words
Total Accepted: 13715 Total Submissions: 76035 My SubmissionsYou are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9]
.
(order does not matter).
解法
最小滑动窗口(Java AC的代码是448ms)
以题目中barfoothefoobarman举例,L中单词长度为3,可以分为
bar|foo|the|foo|bar|man
ba|rfo|oth|efo|oba|rma|n
b|arf|oot|hef|oob|arm|an
这样,针对每个分组,可以利用最小滑动窗口的思想,快速的判断是否包含需要的字符串。
直观上来看,1和2好像都是需要从每个字符开始搜索,实际上,2利用两个指针去在S中寻找满足条件的字符串,并且是每次+wordLen,而且不会重复的去统计,节省了很多时间。
因为L中所有单词的长度是一样的,这样根据wordLen,可以将S分为wordLen组,实际意思是这样的。
以题目中barfoothefoobarman举例,L中单词长度为3,可以分为
bar|foo|the|foo|bar|man
ba|rfo|oth|efo|oba|rma|n
b|arf|oot|hef|oob|arm|an
这样,针对每个分组,可以利用最小滑动窗口的思想,快速的判断是否包含需要的字符串。
直观上来看,1和2好像都是需要从每个字符开始搜索,实际上,2利用两个指针去在S中寻找满足条件的字符串,并且是每次+wordLen,而且不会重复的去统计,节省了很多时间。
代码
public class Solution {
public List<Integer> findSubstring(String S, String[] L) {
List<Integer> retlist = new ArrayList<Integer>();
int wordLen = L[0].length();
int size = L.length;
int slen = S.length();
int max = slen - wordLen + 1;
if(size == 0)
return retlist;
int len_match = wordLen * L.length;
if(len_match > S.length())
return retlist;
HashMap<String, Integer> map = new HashMap<String, Integer>();
for(int i = 0; i< size; ++i){
if(map.containsKey(L[i]))
map.put(L[i],map.get(L[i])+1);
else
map.put(L[i], 1);
}
for(int i = 0; i < wordLen; i++){
//boolean flag = true;
HashMap<String, Integer> tmpMap = new HashMap<String, Integer>();
int count = 0;
int start = i;
for(int j = start; j < max; j += wordLen){
String str = S.substring(j, j + wordLen);
if(!map.containsKey(str)){
tmpMap.clear();
count = 0;
start = j + wordLen;
continue;
}
//map has this str
if(tmpMap.containsKey(str))
tmpMap.put(str, tmpMap.get(str)+1);
else
tmpMap.put(str, 1);
if(tmpMap.get(str) <= map.get(str)){
count++;
}else{
while(tmpMap.get(str) > map.get(str)){
str = S.substring(start, start + wordLen);
tmpMap.put(str, tmpMap.get(str) - 1);
if(tmpMap.get(str) < map.get(str))
count--;
start +=wordLen;
}
}
if(count == size){
retlist.add(start);
str = S.substring(start, start + wordLen);
tmpMap.put(str, tmpMap.get(str)-1);
count--;
start += wordLen;
}
}
}
return retlist;
}
}
结果
Submit Time | Status | Run Time | Language |
---|---|---|---|
15 minutes ago | Accepted | 480 ms | java |
返回
相关博客