题目地址:
中文:https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/
英文:https://leetcode.com/problems/substring-with-concatenation-of-all-words/
题目描述:
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters.
You can return the answer in any order.
Example 1:
Input: s = "barfoothefoobarman", words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
Output: []
Example 3:
Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
Output: [6,9,12]
Constraints:
1 <= s.length <= 10^4
s consists of lower-case English letters.
1 <= words.length <= 5000
1 <= words[i].length <= 30
words[i] consists of lower-case English letters.
思路:
因为每个单词的长度都一样,所以直接截取words单词长度加起来的长度等长的子串比如样例1里,每次取长度6的子串,然后每次取子串单词长度为3的单词,对比words里有没有。
本来是取words的每个单词,与str里进行比较,但是下面这个样例太狠了。。把之前的isOK函数代码推了重写。
这个样例太狠了。。
"ababaab"
["ab","ba","ba"]
题解:
class Solution {
List<Integer> res = new ArrayList<Integer>();
public boolean isOK(String str,String[] words){
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],1);
else {
int j = map.get(words[i]);
map.put(words[i],++j);
}
}
int wordLen = words[0].length();
String s=str;
int l = str.length();
for(int i=0;i<l;i+=wordLen){
s = str.substring(0,wordLen);
//如果map里没有
if(!map.containsKey(s)) return false;
else {
int t = map.get(s);
--t;
map.put(s,t);
if(t<0) return false;
}
str = str.substring(wordLen);
}
//如果map还有剩下的
int temp=0;
for(Integer v:map.values())
{
temp+=v;
if(temp>0) return false;
}
return true;
}
public List<Integer> findSubstring(String s, String[] words) {
String str="";
int wordLen = words[0].length();
int wordsLen = words.length;
int subLen = wordLen*wordsLen;
for(int i=0;i+subLen<=s.length();i++){
str = s.substring(i,i+subLen);
if(isOK(str,words)) res.add(i);
}
return res;
}
}