题目: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"]
You should return the indices: [0,9]
.
(order does not matter).
思路:
定义两个hash表,一个就是传统的把所有的输入进去,对应代号。
本题的一个技巧就是每次从一个位置开始判断,然后再最外面写一个从当前位置判断再这个 start 能否成功的函数:
函数的技巧就是从start位置截取每一个单词的长度,比对是否出现过,出现的次数不能超过1次。
代码:
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { vector<int> res; if(words.empty()) return res; int wordSize=words[0].size(); int totalWords=words.size(); int totalLen=wordSize*totalWords; if(s.size()<totalLen) return res; unordered_map<string,int>wordCount; for(int i=0;i<totalWords;i++){ wordCount[words[i]]++; } for(int i=0;i<=s.size()-totalLen;i++){ if(checkSubstring( s,i, wordCount, wordSize, totalWords)) res.push_back(i); } return res; } bool checkSubstring(string &s,int start,unordered_map<string,int>&wordCount,int wordSize,int totalWords){ if(s.size()-start+1<wordSize*totalWords) return false; unordered_map<string,int>wordFound; for(int i=0;i<totalWords;i++){ string tmp=s.substr(start+i*wordSize,wordSize); if(wordCount[tmp]==0) return false; wordFound[tmp]++; if(wordFound[tmp]>wordCount[tmp]) return false; } return true; } };