leetcode 30. Substring with Concatenation of All Words
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.
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: []
给一组子串,再给一个主串,问主串中是否存在子串组的任意排列组合。
首先枚举起始位置,然后枚举该位置后面的子串是否能满足给定子串组的排列组合,具体是用 unordered_map
来完成(内部用散列表实现)
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
unordered_map<string, int> c;
vector<int> res;
int m=words.size();
for(int i=0;i<m;i++)
c[words[i]]++;
int n=s.length();
if(n==0||m==0)return res;
int len=words[0].length();
for(int i=0;i<n-m*len+1;i++){
unordered_map<string, int> vis;
int j=0;
for(;j<m;j++){
string w=s.substr(i+j*len,len);
if(c.find(w)!=c.end()){
vis[w]++;
if(vis[w]>c[w])break;
}else break;
}
if(j==m)res.push_back(i);
}
return res;
}
};