您的位置:首页 > 其它

LeetCode Substring with Concatenation of All Words

2015-08-12 10:14 162 查看
原题链接在这里: https://leetcode.com/problems/substring-with-concatenation-of-all-words/
这道题思路与Longest Substring Without Repeating Characters 相似。

不同的是这道题需要先生成并维护一个字典,检查新词是否是字典里的词。同时维护一个窗口[start,end], 外层循环是多种取词方法,以例子来说就是分成:

|bar|foo|the|foo|bar|man

b|arf|oot|hef|oob|arm|an

ba|rfo|oth|efo|oba|rma|n

当遇到字典里的词就移动右窗口end,同时用count计数,当遇到非词典里的词时,移动做窗口start,调到最新位置。双指针选取合适的窗口。在移动过程中,为避免重复的词冒充新词,需再生成一个HashMap来计数,若个别词的数量超过原有词的数量时,也需要移动做窗口start直到减掉了多余的词,同时更新count。最后若是出现了符合要求的count,保存start,然后右移一位start来计量新的start position.

Note: 1. 这道题花了好多时间,DP的题目好难。建立内层HashMap要在内层循环以外,这里刚开始错了。

2. 变量尽量少生成些,名字要尽量不同,这种bug真心简直了。

3. count++的条件是<=, 等于时也是要加的;count--的条件是<,等于时说明刚剪掉的是多余的, 减完才会正好等于,所以
count不必减一。

AC Java:

public class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> res = new ArrayList<>();

if(s.length() == 0 || words.length == 0)
return res;

int wordLen = words[0].length();
int sLen = s.length();

HashMap<String, Integer> wordMap = new HashMap<>();
for(int i = 0; i < words.length; i++){
int num  = 1;
if(wordMap.get(words[i])!= null){
num += wordMap.get(words[i]);
}
wordMap.put(words[i],num);
}

for(int i = 0; i <wordLen; i++){

int start = i;
int max = sLen-wordLen+1;
int count = 0;
HashMap<String,Integer> winMap = new HashMap<>(); //error

for(int end = start;end<max;end+=wordLen){
String tempStr = s.substring(end,end+wordLen);
if(!wordMap.containsKey(tempStr)){
winMap.clear();
start = end + wordLen;
count = 0;
continue;
}

if(!winMap.containsKey(tempStr)){
winMap.put(tempStr,1);
}else{
int temp = winMap.get(tempStr);
winMap.put(tempStr,temp+1);
}

if(winMap.get(tempStr) <= wordMap.get(tempStr)){
count++;
}
else{
while(winMap.get(tempStr) > wordMap.get(tempStr)){
String leftStr = s.substring(start,start+wordLen);
winMap.put(leftStr,winMap.get(leftStr)-1); //error
if(winMap.get(leftStr) < wordMap.get(leftStr)) //error
count--;
start+=wordLen;
}
}

if(count == words.length){
res.add(start);
tempStr = s.substring(start,start+wordLen);
winMap.put(tempStr,winMap.get(tempStr)-1);
count--;
start+= wordLen;
}
}
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: