解法速度有点慢,要1000ms 左右,OJ上有人java的答案只要300ms, 不知道大神是怎么写的。。
思路是先把L存成一个HashMap,然后因为L里面word一样长,就可以去check S的substring,在位置 i 每次平移一个wordlength,检查这个word在不在map里,在的话就新建一个curMap再查i+wordLen 到 i + wordLen*2一直查下去,最后比较curMap 和map是不是一致就可以了。
public List<Integer> findSubstring(String S, String[] L) {
if(S == null || L == null || S.length() == 0|| L.length == 0) return null;
List<Integer> ret = new ArrayList<Integer>();
HashMap<String, Integer> map = new HashMap<String, Integer>();
for(String w: L) {
if(map.containsKey(w))
map.put(w, map.get(w)+1);
else map.put(w, 1);
}
int wordLen = L[0].length();
int j = 0;
int i = 0;
while(i + wordLen*L.length <= S.length()) {
j = 0;
String temp = new String(S.substring(i, i+wordLen));
if(map.containsKey(temp)){
HashMap<String, Integer> curMap = new HashMap<String, Integer>();
while(j < L.length) {
temp = new String(S.substring(i + wordLen*(j), i + wordLen*(j+1)));
if(curMap.containsKey(temp))
curMap.put(temp,curMap.get(temp)+1);
else curMap.put(temp, 1);
j++;
}
if(curMap.equals(map)) ret.add(i);
}
i++;
}
return ret;
}