LeetCode 30 - Substring with Concatenation of All Words
来源:互联网 发布:c语言产生0 9的随机数 编辑:程序博客网 时间:2024/05/01 17:37
Substring with Concatenation of All Words
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).
My Code
class Solution {public: vector<int> findSubstring(string s, vector<string>& words) { int words_size = words.size(); int word_len = words[0].length(); int s_len = s.length(); unordered_map<string, int> words_cnt; for (int i = 0; i < words_size; i++) words_cnt[words[i]]++; vector<int> indices; for (int i = 0; i <= s_len - words_size * word_len; i++) { unordered_map<string, int> occurences; bool flag = true; for (int j = 0; j < words_size; j++) { string word = s.substr(i + j * word_len, word_len); if (words_cnt.find(word) != words_cnt.end()) occurences[word]++; else { flag = false; break; } if (occurences[word] > words_cnt[word]) { flag = false; break; } } if (flag) indices.push_back(i); } return indices; }};Runtime: 776 ms
Notice
There may be duplicate word in words. So we need one more unordered_map to record count of each word.
0 0
- 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 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
- Substring with Concatenation of All Words -- LeetCode
- Leetcode: Substring with Concatenation of All Words
- leetcode:Substring with Concatenation of All Words
- LeetCode|Substring with Concatenation of All Words
- maven web项目的几种部署方式和常见的出错方式的解决
- [C++11]_[初级]_[shared_ptr的使用场景]
- CodeForces 626 A. Robot Sequence(水~)
- C/C++基础::sizeof() 与 sizeof(string)
- 文件合成器
- LeetCode 30 - Substring with Concatenation of All Words
- iOS initWithFrame:frame] 与 [UIButton buttonWithType] 对比
- 第三方框架
- 空悲切
- Android 三种跨界面的通讯方式
- css滚动条样式制定 jscrollpane
- android中用户头像设置的一点心得——关于bitmap被回收的问题
- (八)利用processing实现类似吃豆人的运行效果
- js javascript:void(0) 真正含义