leetCode_Substring with Concatenation of All Words
来源:互联网 发布:mac屏保设置不生效 编辑:程序博客网 时间:2024/06/05 09:28
题意:给定一个字符串s和一个组等长的单词序列t,返回子串的开始坐标,子串为单词序列中所有单词的连接(只出现一次),顺序不重要。
例如:s="barfoothefoobarman" words:["foo","bar"] 返回的字典序列[0,9]
思路:非常简单,用map记录单词序列出现的次数,然后从每个index开始,看看t.size()*t[0].length()这个区间内是否把t所有的单词都出现了。【代码中有一个要注意】
注意优化:新开一个map表示子串中单词出现的个数,从0累加。不要首先将值复制一遍,出现一个单词减一个单词,这样会超时。
代码如下:
vector<int> findSubstring(string s, vector<string>& words){ vector<int> ans; vector<vector<int> > indexes; vector<int> isUsed; map<string,int> wordsIndex; vector<int> tempVector; int i,j,k,t=0; if(s.length()==0 || words.size()==0 || s.length()<words[0].length()*words.size()) return ans; for(i=0;i<words.size();i++) wordsIndex[words[i]]++; for(i=0;i<s.length()-words[0].length()*words.size()+1;i++) { map<string,int> temp; t=min(i+words[0].length()*words.size(),s.length()); k=0; for(j=i;j<t;j=j+words[0].length()) { string ss=s.substr(j,words[0].length()); if(wordsIndex.find(ss)!=wordsIndex.end()) { temp[ss]++; k++; if(temp[ss]>wordsIndex[ss]) { k--; break; } } } if(k==words.size()) ans.push_back(i); } return ans;}
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
- LeetCode29: Substring with Concatenation of All Words
- [Leetcode] Substring with Concatenation of All Words
- Substring with Concatenation of All Words
- Substring with Concatenation of All Words
- [LeetCode]Substring with Concatenation of All Words
- Substring with Concatenation of All Words
- LeetCode-Substring with Concatenation of All Words
- [LeetCode] Substring with Concatenation of All Words
- 26 - 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
- 如果你也和我一样茫然
- java集合框架概述
- GreenDao查询,有时会查不到数据,解决方法。
- spring Bean的实例化
- Android中当一行显示两个TextView时,第一个可“…”,而第二个必须显示全部
- leetCode_Substring with Concatenation of All Words
- extjs中如何监听textfield的改变
- CSU 1811 Tree Intersection
- 求素数算法(C语言)
- 面试题34:丑数
- undefined reference to `clock_gettime' 链接错误问题解决
- Dubbo架构设计详解
- 无法访问项目中jsp解决方法
- HTML前端开发上乘"武学"-nodeJS