leetcode30---Substring with Concatenation of All Words
2015-12-22 15:29
405 查看
问题描述:
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
For example, given:
You should return the indices: [0,9].
(order does not matter).
问题求解:
用到哈希map:unordered_map.
(1)
(2)
(3)依次检查每一个可能的起点i
代码:
结果:
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
For example, given:
s: "barfoothefoobarman" words: ["foo", "bar"]
You should return the indices: [0,9].
(order does not matter).
问题求解:
用到哈希map:unordered_map.
(1)
unordered_map<string,int> num;用来记录words中每一个word,及其出现的次数 num[word].
(2)
unordered_map<string, int> match;//记录与word匹配的sword,及其匹配次数
(3)依次检查每一个可能的起点i
如果没有匹配成功,或者word匹配次数超过了words中该word的数量,跳到下一个i; 如果成功完成此次检查,则i即为满足的起点,将i放入res;
代码:
#include <iostream> //#include<cstring> #include<vector> #include<unordered_map> using namespace std; class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { unordered_map<string,int> num; //for(string word:words) //num[word]++;//num[word]记录words中每一个word出现的次数 for(unsigned int i=0;i<words.size();i++) { num[words[i]]++;//num[word]记录words中每一个word出现的次数 } int slen=s.size(); int wordslen=words.size(); int wordlen=words[0].size();//每个word长度相同 vector<int> res;//存储结果 for(int i=0;i<slen-wordslen*wordlen+1;i++) {//slen-wordslen*wordlen为s与words进行最后一个匹配的起点 int j; unordered_map<string, int> match;//记录与word匹配的sword,及其匹配次数 for(j=0;j<wordslen;j++) {//对words中的每一个word而言 //以i+j*wordlen为起点,在s中找到与每个word长度一样的sword string sword=s.substr(i+j*wordlen, wordlen); if(num.find(sword) != num.end()) {//如果当前sword匹配 match[sword]++; //防止类似情况s="abcdcdef",words=["cd","ef"],sword="cd" if(match[sword] > num[sword]) break; } //如果不匹配,跳到下一个i起点 else break; } //如果成功完成检测,当前起点i符合 if(j==wordslen) res.push_back(i); } return res; } }; int main() { Solution s; vector<int> res;//存储结果 string str="barfoothefoobarman"; vector<string> words={"foo","bar"}; res=s.findSubstring(str, words); for(unsigned int i=0;i<res.size();i++) { cout<<res[i]<<" "; } cout<<endl; return 0; }
结果:
0 9 Process returned 0 (0x0) execution time : 0.208 s Press any key to continue.
相关文章推荐
- android Google Map获取地理位置信息的方法
- Spark RDD API详解(一) Map和Reduce
- Python中map()函数浅析
- Android使用Google Map浅谈
- Erlang中的映射组Map详细介绍
- c++中map的基本用法和嵌套用法实例分析
- JavaScript中实现Map的示例代码
- jquery中map函数与each函数的区别实例介绍
- jquery中map函数遍历数组用法实例
- jquery与google map api结合使用 控件,监听器
- jquery遍历数组与筛选数组的方法
- JavaScript中实现map功能代码分享
- 用json方式实现在 js 中建立一个map
- Android Map新用法:MapFragment应用介绍
- js Map List 遍历使用示例
- java实现遍历Map的方法
- velocity显示List与Map的方法详细解析
- Google Map Api和GOOGLE Search Api整合实现代码
- 关于STL中的map容器的一些总结
- Javascript实现的Map集合工具类完整实例