30. Substring with Concatenation of All Words
题目:在s找到所有words中所有字符串串起来的子字符串(包括words中所有字符串)的起始位置
思路:参考了别人的解法,but超时,记录一下。将words中的所有单词建一个HashMap,单词和出现次数。每次新建一个cp复制前面的HashMap,截取words总长度子串,在cp中能找到就移除或次数减1,遍历完看cp是否为空,为空则加到list中。简单粗暴的解法,但是复杂度高。
public class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> ret = new LinkedList<>();
int s_len = s.length();
int w_len = words.length;
int w0_len = words[0].length();
if(s_len < w_len*w0_len) return ret;
HashMap<String, Integer> hm = new HashMap<>();
for(String sw: words){
if(hm.containsKey(sw)) hm.replace(sw, hm.get(sw)+1);
else hm.put(sw, 1);
}
for(int i = 0; i <= s_len-w_len*w0_len; i++){
HashMap<String, Integer> cp = new HashMap<>(hm);
String s_per = s.substring(i, i+w_len*w0_len);
for(int j = 0; j <= w_len*w0_len-w0_len; j += w0_len){
String s_per_per = s_per.substring(j, j+w0_len);
if(cp.containsKey(s_per_per)){
if(cp.get(s_per_per) == 1){
cp.remove(s_per_per);
}
else{
cp.replace(s_per_per, cp.get(s_per_per)-1);
}
}
else{
break;
}
}
if(cp.isEmpty()) ret.add(i);
}
return ret;
}
}
Two Pointer——