30. Substring with Concatenation of All Words
2017-06-29 23:08
281 查看
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).
解决该问题的关键是理解清楚要求。
给定一个目标字符串s,一个单词集合words。
要求使得words集合中所有元素连续出现在s中的首位置组成的集合(元素顺序不考虑)。
正如所给实例,目标字符串s: “barfoothefoobarman”
对比单词集合words: [“foo”, “bar”]
我们发现,在pos=0 ~ 5时“barfoo”恰好匹配,则0压入结果vector;
在pos=9 ~ 14时“foobar”恰好匹配,则9压入结果vector;
For example, given:
s: “barfoothefoobarman”
words: [“foo”, “bar”]
You should return the indices: [0,9].
(order does not matter).
解决该问题的关键是理解清楚要求。
给定一个目标字符串s,一个单词集合words。
要求使得words集合中所有元素连续出现在s中的首位置组成的集合(元素顺序不考虑)。
正如所给实例,目标字符串s: “barfoothefoobarman”
对比单词集合words: [“foo”, “bar”]
我们发现,在pos=0 ~ 5时“barfoo”恰好匹配,则0压入结果vector;
在pos=9 ~ 14时“foobar”恰好匹配,则9压入结果vector;
vector<int> findSubstring(string s, vector<string>& words) { if (words.empty())return vector<int>(); vector<int> res; unordered_map<string, int> word_cnt; for (auto x : words)word_cnt[x]++; int word_size = words[0].size(); int word_nums = words.size(); int s_size = s.size(); int i = 0, j = 0; int len = s_size - word_size * word_nums + 1; for (i = 0; i < len; i++){ unordered_map<string, int> temp_count; for (j = 0; j < word_nums; j++){ string word = s.substr(i + j * word_size, word_size); if (word_cnt.find(word) != word_cnt.end()){ ++temp_count[word]; if (temp_count[word] > word_cnt[word])break; } else break; } if (j == word_nums)res.push_back(i); } return res; }
相关文章推荐
- leetcode--30. Substring with Concatenation of All Words
- LeetCode - 30. Substring with Concatenation of All Words
- 30 Substring with Concatenation of All Words
- [LeetCode-Algorithms-30] "Substring with Concatenation of All Words" (2017.9.22-WEEK3)
- 30. Substring with Concatenation of All Words
- [leetcode] 30 Substring with Concatenation of All Words
- leetcode 30. Substring with Concatenation of All Words
- 30. Substring with Concatenation of All Words
- LeetCode 30. Substring with Concatenation of All Words(单词连接)
- 30. Substring with Concatenation of All Words
- 30. Substring with Concatenation of All Words
- FTPrep, 30 Substring with Concatenation of All Words
- LeetCode 30 Substring with Concatenation of All Words
- leetcode 30 Substring with Concatenation of All Words
- LeetCode 30. Substring with Concatenation of All Words
- 30. Substring with Concatenation of All Words
- 30. Substring with Concatenation of All Words
- [leetcode]30. Substring with Concatenation of All Words@Java
- leetcode 30. Substring with Concatenation of All Words
- [LeetCode] 30. Substring with Concatenation of All Words 解题思路 - Java