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: []
考察:字符串查找,題目意思:給定字符串s,words是一個字符串數組 ,每個字符串的長度是一樣。這裏我們設words數組長度爲m,每個字符串的長度爲n,求這m個字符串拼接成m*n的大字符串在S出現的index。
使用unordered_map 保存words字符串出現的次數,進行哈希映射判斷;然後枚舉s的每個index作爲起始位置,切割字符串進行查找判斷;
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
if (s.empty() || words.empty() || s.length() < words.size()*words[0].size())
return {};
vector<int> res;
unordered_map<string, int> m1;
for (int i = 0; i < words.size(); i ++)
m1[words[i]] ++;
int m = words.size(), n = words[0].size();
for (int i = 0; i <= s.length()-m*n; i ++) {
unordered_map<string, int> m2;
int j;
for (j = 0; j < m; j ++) {
string seg = s.substr(i+j*n, n); //切割
if (m1.find(seg) == m1.end()) //是否在m1出現,沒出現,則此i不符合
break;
m2[seg] ++;
if (m1[seg] < m2[seg]) // 出現次數多了,則此i不符合
break;
}
if (j == m) // 此i符合
res.push_back(i);
}
return res;
}
};
完,