您的位置:首页 > 其它

Substring with Concatenation of All Words

2016-06-30 16:44 288 查看
参考小莹子同学的点击打开链接

自己刚才一直在纠结这段code,其实就是保证还剩下最后一个当前满足条件的word能留下。

if (curDict.get(temp) < dict.get(temp)) {
count--;
}
ArrayList<Integer> list = findSubstring("barfoofoobarthefoobarman",
new String[]{"foo",
"bar","the"});

用这个测一下吧。
public class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> res = new LinkedList<>();
if (s == null || s.length() == 0 || words == null || words.length == 0) {
return res;
}
int num = words.length;
Map<String, Integer> dict = new HashMap<>();
for (String word: words) {
if (dict.containsKey(word)) {
dict.put(word, dict.get(word) + 1);
} else {
dict.put(word, 1);
}
}
int wordLen = words[0].length();
for (int i = 0; i < wordLen; i++) {
int index = i;
int count = 0;
Map<String, Integer> curDict = new HashMap<>();
//for (int j = i; j < s.length() - wordLen; j = j + wordLen) {
for (int j = i; j <= s.length() - wordLen; j = j + wordLen) {
String word = s.substring(j, j + wordLen);
if (!dict.containsKey(word)) {
//index = j;
index = j + wordLen;
curDict.clear();
count = 0;
continue;
}

if (curDict.containsKey(word)) {
curDict.put(word, curDict.get(word) + 1);
} else {
curDict.put(word, 1);
}
if (curDict.get(word) <= dict.get(word)) {
count++;
} else {
while (curDict.get(word) > dict.get(word)) {
String temp = s.substring(index, index + wordLen);
curDict.put(temp, curDict.get(temp) - 1);
if (curDict.get(temp) < dict.get(temp)) {
count--;
}
index = index + wordLen;
}
}
if (count == num) {
res.add(index);
String temp = s.substring(index, index + wordLen);
curDict.put(temp, curDict.get(temp) - 1);
count--;
index = index + wordLen;
}
}
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: