LeetCode 30. Substring with Concatenation of All Words
2016-04-15 11:09
363 查看
问题
https://leetcode.com/problems/substring-with-concatenation-of-all-words/解法
经过测试,words中的字符串存在重复的情况。因此第一步是统计每种字符串个数。
然后在s中进行枚举,比较当前串是否符合。
在枚举s时使用滑动窗口算法。
typedef unordered_map<string, int>::iterator it; class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { vector<int> ret; if (words.size() < 1) return ret; int wdLen = words[0].size(); if (s.size() <wdLen* words.size()) return ret; unordered_map<string, int> wdCnt; for(int i=0; i< words.size(); ++i) wdCnt[words[i]]++; for (int i=0; i<wdLen; ++i) { int left = i; unordered_map<string, int> found; int foundNum = 0; for(int j = i; j + wdLen<=s.size(); j+= wdLen) { string sub = s.substr(j, wdLen); if(wdCnt.find(sub) == wdCnt.end()) { found.clear(); foundNum =0; left = j+wdLen; }else{ found[sub]++; foundNum++; if (found[sub] > wdCnt[sub]) { while(found[sub] > wdCnt[sub]) { string ss = s.substr(left, wdLen); found[ss]--; foundNum--; left+= wdLen; } } if (foundNum == words.size()) { ret.push_back(left); string ss = s.substr(left, wdLen); found[ss]--; foundNum--; left+=wdLen; } } } } return ret; } };
实现细节
unordered_map<> clear()Clear content
All the elements in the unordered_map container are dropped: their destructors are called, and they are removed from the container, leaving it with a size of 0.
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解