You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening
characters.
For example, given:
s: "barfoothefoobarman"
words: ["foo", "bar"]
给定一个字符串s及一个字符串数组words,找到所有位置index,这些s.substring(index,index+words[0].length()*words.length)包含了所有words的词组,例如barfoothefoobarman 的0-5包含"foo", "bar"这些就符合要求。
由于words里面的单词,每个单词长度一样,可以重复,所以还是要用map记录每个词出现的次数,所以先构造关于words的map<String,Integer>
然后每次从s中取words所有词总长度相等的子串,然后去map中匹配即可。
这种方法效率一般,要注意循环里避免new对象
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> result = new ArrayList<Integer>();
if(s==null||words==null||words.length<1||words[0].length()*words.length>s.length())
return result;
Map<String ,Integer> map = new HashMap<String ,Integer>();
for(int i=0;i<words.length;i++){
if(map.containsKey(words[i])){
map.put(words[i], map.get(words[i])+1);
}
else{
map.put(words[i], 1);
}
}
int len = words[0].length();
for(int i=0;i+words.length*len<=s.length();i++){
if(isMatch(s.substring(i,i+words.length*len),map,len ))
result.add(i);
}
return result;
}
public static boolean isMatch(String s,Map<String ,Integer> map,int len) {
Map<String ,Integer> tempMap = new HashMap<String ,Integer>(map);
for(int i=0;i*len<s.length();i++){
String str = s.substring(i*len, i*len+len);
if(!tempMap.containsKey(str)|| tempMap.get(str)<1){
return false;
}
else
tempMap.put(str, tempMap.get(str)-1);
}
return true;
}