leetcode第一刷_Substring with Concatenation of All Words
来源:互联网 发布:微信淘宝优惠券可靠吗 编辑:程序博客网 时间:2024/06/05 11:34
这道题我并没有想到太好的解法,用了两个map,时间效率很差,勉强过了。
要求一个字串,是字典里所有单词的一个种组合。显然不能先求出所有组合,再看是不是字串,这时间复杂度太高。还好题目中说明了所有单词的长度是一样的,这大大简化了操作。我的做法是建立一个map,这个map以单词为键,以出现次数为值,哈哈,没想到吧~这里很容易忽视的一个问题是同一个单词可能在字典里存了多次。然后开始扫字符串,每次取单词长度,看看在不在字典里,在的话就把可用个数减1,这也就是为什么要用两个map,一个用来保存原始情况,一个用来中间处理。如果出现可用个数小于0的情况,说明这一段是不行的,应该pass掉。
这里我有一个很纠结的问题,就是下次开始的位置,这个位置应该每次只移动1,还是像kmp那样每次找一个前面匹配的位置回退一下。回头应该验证一下。
class Solution {public: vector<int> findSubstring(string S, vector<string> &L) { vector<int> res; int msize = L.size(); if(msize == 0) return res; int len = L[0].length(); int olen = msize*len; int slen = S.length(); map<string, int> visited, vis; for(int i=0;i<msize;i++){ visited[L[i]]++; } int scope = slen-olen; string tp; for(int i=0;i<=scope;i++){ int j=0; vis = visited; for(;j<olen;j+=len){ tp = S.substr(i+j, len); if(vis[tp]<=0) break; vis[tp]--; } if(j == olen){ res.push_back(i); } vis.clear(); } }};
0 0
- leetcode第一刷_Substring with Concatenation of All Words
- 0030_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
- LeetCode - Substring with Concatenation of All Words
- Substring with Concatenation of All Words -- LeetCode
- Leetcode: Substring with Concatenation of All Words
- 理解VMWare的三种网络连接模式(bridged、NAT、host-only)
- Android导出jar包后的资源使用问题
- s:iterator遍历 object.List<List<String>>
- Win7x64下VC6.0的一些蛋疼的问题+解决方案。
- 为VMware里的虚拟机设置静态IP
- leetcode第一刷_Substring with Concatenation of All Words
- 上司
- Flex 4.1 + BlazeDS(Demo实例)实现信息订阅推送
- 停止
- 图形学中的贴图采样、走样与反走样等
- 你若不来
- cocos2d-x 3.0 内存管理
- 九度题目1363:欢乐斗地主
- SEO一定要是可控的