Leetcode(10) - Substring with Concatenation of All Words
2017-05-07 23:18
337 查看
https://leetcode.com/problems/substring-with-concatenation-of-all-words/#/description
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:
words:
You should return the indices:
(order does not matter).
Solution:
这道题的解法是,从前往后遍历string s,每次遍历当前位置的words.size() * words[0].length()的substring,用两个Map来记录words是否匹配,当匹配则将i放入返回值中。
这里有个小错误,我一开始以为words不会重复,所以用了set,但是,好吧,好坑。
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).
Solution:
这道题的解法是,从前往后遍历string s,每次遍历当前位置的words.size() * words[0].length()的substring,用两个Map来记录words是否匹配,当匹配则将i放入返回值中。
这里有个小错误,我一开始以为words不会重复,所以用了set,但是,好吧,好坑。
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { vector<int> indexs; map<string, int> words_set; for(string word : words) { words_set[word]++; } int word_len = words[0].length(); for(int i = 0; i < s.length() - words.size() * word_len + 1; i++) { map<string, int> exist; int stop_index = i + words.size() * word_len; for(int start = i; start < stop_index;) { string s2 = s.substr(start, word_len); if(words_set.find(s2) != words_set.end()) { exist[s2]++; if(exist[s2] <= words_set[s2]) { start += word_len; if(start == stop_index) { indexs.push_back(i); } else { continue; } } } break; } } return indexs; } };
相关文章推荐
- 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] 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: Substring with Concatenation of All Words
- leetcode 71: Substring with Concatenation of All Words
- [LeetCode] Substring with Concatenation of All Words
- leetcode 102: Substring with Concatenation of All Words
- LeetCode Substring with Concatenation of All Words暴力法暴力法更加暴力的方法
- LeetCode: Substring with Concatenation of All Words
- LeetCode29: 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] Substring with Concatenation of All Words
- [leetcode]Substring with Concatenation of All Words