LeetCode 30. Substring with Concatenation of All Words
2017-05-26 21:36
357 查看
题意
给定一个字符串和一个单词集合,要求找出连续的子序列的首地址,这个子序列中必须连续且完全出现单词集合内的单词思路
对单词集合内单词进行Hash计数,然后遍历字符串,判断中间记录出现的单词是否集合内,然后检查集合内单词是否全部出现需要注意的case:
单词有可能多次出现,且在子串中出现次数大于集合内单词数,所以在检查单词的时候不仅要检查单词是否在集合中,还要注意当前单词之前的出现次数已经达到要求.
代码
class Solution { public: map<string, int>mp; vector<int> findSubstring(string s, vector<string>& words) { vector<int>ans; size_t cnt = words.size(); mp.clear(); for(size_t i = 0; i < cnt;i++){ mp[words[i]]++; } size_t wordLen = words[0].length(); size_t len = s.length(); for(size_t i = 0; i < len - cnt * wordLen + 1;i++){ size_t flag = 0; size_t j = i; map<string,int>mp2; while(j + wordLen - 1 < len){ string str = ""; for(size_t q = 0; q < wordLen;q++){ str += s[j + q]; } if(mp[str] > 0){ mp2[str]++; mp[str]--; j += wordLen; } else { break; } } for(size_t k = 0; k < cnt;k++){ if(mp[words[k]] != 0){ flag = 1; break; } } for(size_t k = 0; k < cnt;k++){ if(mp2[words[k]] > 0){ mp[words[k]] += mp2[words[k]]; mp2[words[k]] = 0; } } if(flag == 0){ ans.push_back(i); } } return ans; } };
相关文章推荐
- [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_OJ【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
- 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 30 Substring with Concatenation of All Words (C,C++,Java,Python)
- LeetCode 30 - Substring with Concatenation of All Words
- leetcode 30 Substring with Concatenation of All Words
- LeetCode 30 Substring with Concatenation of All Words 解法为Hashmap
- leetCode 30.Substring with Concatenation of All Words (words中所有子串相连) 解题思路和方法