leetcode 30. Substring with Concatenation of All Words
2017-08-30 13:20
344 查看
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).
一眼看过去,以为是ac自动机。
后来看题目发现真难懂,看了看网上的解释,懂了。
题目意思转换一下就是求,words里面的单词排列组合成 k 求k 在s中出现的位置。
比如
"wordgoodgoodgoodbestword"
["word","good","best","good"]
words里面有4个单词,排列组合出24种字符串k。然后找出k在字符串中s出现的位置。
当然写代码时我们不能把24种组合都求出来,可以用map处理嘛。
时间复杂度O(n*m*len(s)) n*m为words中所有单词加起来的长度
For example, given:
s:
"barfoothefoobarman"
words:
["foo", "bar"]
You should return the indices:
[0,9].
(order does not matter).
一眼看过去,以为是ac自动机。
后来看题目发现真难懂,看了看网上的解释,懂了。
题目意思转换一下就是求,words里面的单词排列组合成 k 求k 在s中出现的位置。
比如
"wordgoodgoodgoodbestword"
["word","good","best","good"]
words里面有4个单词,排列组合出24种字符串k。然后找出k在字符串中s出现的位置。
当然写代码时我们不能把24种组合都求出来,可以用map处理嘛。
时间复杂度O(n*m*len(s)) n*m为words中所有单词加起来的长度
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { vector<int> ans; int n = words.size(); if (n == 0) return ans; int m = words[0].size(); unordered_map<string, int> mp; for (int i = 0; i < n; ++i) { mp[words[i]]++; } for (int i = 0; i + n*m <= s.size(); ++i) { int num = 0; unordered_map<string, int> mp2 = mp; for (int j = 0; j < n; ++j) { string tmp = s.substr(i + j*m, m); if (mp2[tmp] > 0) num++; mp2[tmp]--; } if (num != n) continue; ans.push_back(i); } return ans; } };
相关文章推荐
- LeetCode-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
- [leetcode] 30. Substring with Concatenation of All Words 解题报告
- [*leetcode 30] Substring with Concatenation of All Words
- leetcode 30. Substring with Concatenation of All Words
- LeetCode_OJ【30】Substring with Concatenation of All Words
- leetcode 30 Substring with Concatenation of All Words (java)
- 【C++】 LeetCode 30. Substring with Concatenation of All Words
- LeetCode 30. Substring with Concatenation of All Words(词语拼接组合)
- [leetcode]30. Substring with Concatenation of All Words@Java
- 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
- leetcode 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
- leetcode--30. Substring with Concatenation of All Words