https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/
基本上就是从头到尾扫描,每次移动一格,不断地在hashmap中删除一个匹配到的字符串。
这里有一个问题。题目中没有讲明L中有重复,而实际上是会有重复的。
leetcode这里写得不是太清楚。所以我们用hashmap来记录各个字串出现的次数。
一开始我用的递归,老是会超时,改为for后就ok了,实际上这个程序使用for来写也不费劲。
public class Solution {
public List findSubstring(String S, String[] L) {
ArrayList rst = new ArrayList();
if (S == null || L == null || L.length == 0) {
return rst;
}
HashMap s1 = new HashMap();
for(String s: L) {
if (s1.containsKey(s)) {
s1.put(s, s1.get(s) + 1);
} else {
s1.put(s, 1);
}
}
int len = S.length();
int sLen = L[0].length();
// 用i来控制扫描的起始位置
for (int i = 0; i <= (len - L.length * sLen); i++) {
HashMap left = new HashMap(s1);
// 用j来表示在本次扫描到达的匹配位置
for (int j = i; j <= len - sLen; j+=sLen) {
String tmp = S.substring(j, j + sLen);
if (left.containsKey(tmp)) {
if (left.get(tmp) == 1) {
left.remove(tmp);
} else {
left.put(tmp, left.get(tmp) - 1);
}
// 将匹配位置往前移动
} else {
// 移动到下一个位置
break;
}
if (left.isEmpty()) {
rst.add(i);
break;
}
}
}
return rst;
}
}