<30>——Substring with Concatenation of All Words
2017-09-09 20:21
183 查看
30、Substring with Concatenation of All Words
子字符串连接的单词
现有一组长度相等的字符串words,要在原字符串中找出正好包含words中所有字符串的子字符串的起始位置。例子:
输入: s = “barfoothefoobarman”, words = [“foo”, “bar”]输出: [0, 9]
分析:
(unordered_map<关键字,值>无序map类型)1.这道题是寻找子字符串的深化版本,寻找的子字符串是由多个等长的字符串连接在一起的,难点就在于子字符串之间没有先后顺序。
2.就是我们需要确保每一个子字符串都只出现了一次,所以我们需要两个unordered_map<string,int>来存储字符串和他的出现次数,一个做为对比模板,一个做为查找计数。
3.迭代原字符串,每当找到一个同words中的字符串时,就进入循环类比接下来同样长度的字符串中是否与words相同且不重复,达成则记录迭代,否则break。
代码:
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { unordered_map<string,int> compare;//比较模板 for(string w:words) compare[w]++; int n=s.length(),num=words.size(),len=words[0].length(); vector<int> res; for(int i=0;i<=n-num*len+1;i++) { unordered_map<string,int>counts;//计数 int j=0; for(;j<num;j++) { string word=s.substr(i+j*len,len);//复制 if(compare.find(word)!=compare.end()) { counts[word]++; if(counts[word]>compare[word]) break; } else break; } if(j==num)res.push_back(i); } return res; } };
相关文章推荐
- 30. Substring with Concatenation of All Words
- LeetCode 30 Substring with Concatenation of All Words
- Substring with Concatenation of All Words——解题报告(窗口移动法)
- Substring with Concatenation of All WordsTotal
- leetcode30---Substring with Concatenation of All Words
- [LeetCode][Java] Substring with Concatenation of All Words
- leetcode 30. Substring with Concatenation of All Words
- LeetCode 30 - Substring with Concatenation of all words
- LeetCode: Substring with Concatenation of All Words
- [leetcode]Substring with Concatenation of All Words
- 【ATT】Substring with Concatenation of All Words
- 30. Substring with Concatenation of All Words *HARD*
- LeetCode: Substring with Concatenation of All Words [029]
- LeetCode-Substring with Concatenation of All Words
- Leetcode -- Substring with Concatenation of All Words
- [LeetCode] Substring with Concatenation of All Words
- leetcode_Substring with Concatenation of All Words
- leetcode 102: Substring with Concatenation of All Words
- leetcode 30. Substring with Concatenation of All Words
- LeetCode: Substring with Concatenation of All Words