Substring with Concatenation of All Words
2016-01-19 00:57
281 查看
原题链接
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 wordsexactly once and without any intervening characters.
For example, given:
s:
words:
You should return the indices:
(order does not matter).
代码如下(这道题目题意理解有问题,只能通过约75%的测试用例):
一个未通过的测试用例如下(s中good可以多于‘词典’中的个数):
Input:"wordgoodgoodgoodbestword" ["word","good","best","good"]
Output:[]
Expected:[8]
算法思路:
我对于该题的题意理解与题目(给出的一个测试用例未能通过)本身应当是有分歧的,我是认为应当长度(也就是单词个数)应当一致才算匹配成功并返回其首字母下标!!
我们假定词典中有wordNum个单词。
每次都从s中挑选wordLen*wordNum长度的连续字符串str进行判定。我们对其中进行统计,一旦发现满足下面任何一个条件:
(1)在词典dic中没有找到给定单词;
(2)str中的某个单词的统计个数超过了dic中该单词的个数。
我们即认为该str是不满足条件的,str应当向前移动一个单词的长度。否则将str的首字母的indices添加到结果集合中,同时str向前移动一个单词的长度。
重复前面(紫色部分)的操作。
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 wordsexactly 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).
代码如下(这道题目题意理解有问题,只能通过约75%的测试用例):
一个未通过的测试用例如下(s中good可以多于‘词典’中的个数):
Input:"wordgoodgoodgoodbestword" ["word","good","best","good"]
Output:[]
Expected:[8]
算法思路:
我对于该题的题意理解与题目(给出的一个测试用例未能通过)本身应当是有分歧的,我是认为应当长度(也就是单词个数)应当一致才算匹配成功并返回其首字母下标!!
我们假定词典中有wordNum个单词。
每次都从s中挑选wordLen*wordNum长度的连续字符串str进行判定。我们对其中进行统计,一旦发现满足下面任何一个条件:
(1)在词典dic中没有找到给定单词;
(2)str中的某个单词的统计个数超过了dic中该单词的个数。
我们即认为该str是不满足条件的,str应当向前移动一个单词的长度。否则将str的首字母的indices添加到结果集合中,同时str向前移动一个单词的长度。
重复前面(紫色部分)的操作。
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { vector<int> res; int wordLen=words[0].size(),wordNum=words.size(); if(s.size()<wordLen*wordNum) return res; map<string,int> dic,curWord; for(int i=0;i<wordNum;i++) dic[words[i]]++; for(int i=0;i<s.size()-wordLen*wordNum;i++) { curWord.clear(); int j; for(j=0;j<wordNum;j++) { string word=s.substr(i+j*wordLen,wordLen); if(dic.find(word)==dic.end()) break; curWord[word]++; if(curWord[word]>dic[word]) break; } if(j==wordNum) res.push_back(i); } return res; } };
相关文章推荐
- javascript捕获键盘组合事件
- (一二〇)抽象数据类型
- 疾病尚需用猛药
- 【C语言】冒泡排序及优化
- (一一九)类作用域
- 学习java的道路
- (一一八)对象数组
- hypervisor on vehicle
- 设计模式之代理模式(二结构型)
- (一一七)this指针
- http servlet服务器和android客户端(二)第一个android客户端
- 单例模式的应用
- 进程间通信(IPC) 之 共享内存 和 闲扯其他一些东西
- python3 crontab 下运行python输出中文失败
- MonoBehaviour继承类及其重要方法
- 敏捷开发解决方案
- 敏捷团队的规范与准则
- 移除未排序链表中的重复结点
- Spark 快速理解
- (一一六)类的构造函数和析构函数