【leetcode】Substring with Concatenation of All Words
来源:互联网 发布:ubuntu 14 32位下载 编辑:程序博客网 时间:2024/06/03 17:02
题目:
给定一个字符串S,一个字符串数组L,找出S中所有这样的子串起点,该子串包含L中的所有元素。
说明:
1)L中存在重复的元素
2)子串不允许间断,即子串从开始到找全L中的所有元素之前,子串中不允许包含L以外的东西,而且,即使当前处理的子串是L中含有的,但是前面已经找够了,这个多余的也是不合法的,若此时还有L中的其他元素没找到,从这个起点开始也是不成功的。
3)L在S中出现的顺序不同考虑,任意顺序,只要全部存在就可以。
分析:
1)先对L中的所有元素做个统计,定义一个hash map<string, int> 型 变量total,统计每个词出现的次数,另外定义一个同类型的has_find,用来记录到目前为止,已经找到的L中的元素情况,当全部找全的时候就找到了一个合法的起始点。然后将has_find清空,继续找。
2)整体的框架与传统的字符串匹配一致,不同的是这里不要求顺序,所以似乎在S中不能加速移动。
实现:
vector<int> findSubstring(string S, const vector<string> &L) {vector<int> re;if(S.size() == 0 || L.size() == 0)return re;unordered_map<string, int> total;unordered_map<string, int> has;int wordNum = L.size();int wordLen = L[0].size();int searchEnd = S.size() - wordLen * wordNum;for (int i = 0; i < wordNum; ++i){total[L[i]]++;}for (int i = 0; i <= searchEnd; ++i){int j = i;has.clear();int iword = 0;for (; iword < wordNum; ++iword){string sub = S.substr(j, wordLen);//not in Lif(total[sub] == 0)break;//in L, but redundancyif(++has[sub] > total[sub])break;j += wordLen;}if(iword == wordNum){re.push_back(i);}}return re;}
后记:
程序跑了1400多毫秒,这几乎是目前为止时间最久的一个题了,看来有更好的算法?
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
- Sort List
- Android多线程文件下载器
- tableview的两个取得重用cell方法的区别
- java中Comparator实现两个对象比较
- 修改WAMP默认的80端口
- 【leetcode】Substring with Concatenation of All Words
- 编程之美--只考加法的面试题1
- rac 介绍
- Lua和C语言的交互2【转】
- Lua和C语言的交互3【转】
- codeforces 133A HQ9+(字符串水题)
- 求n!末尾0的个数以及 最末尾 1的位置
- HDU 4280 Island Transport 网络流
- “多线程IO”和“单线程异步IO”的对比【转】