30. Substring with Concatenation of All Words (String, Map)
2015-09-20 13:51
417 查看
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).
思路: 判断一个值是否包含在一个数组中,首先应该想到将这个数组中的元素放入HashTable,否则每次查找都需要O(n)的时间复杂度。
时间复杂度:O(n*size),其中n为s的长度,size是指数组words包含多少个元素。当words元素不多的时候,我们可以说时间复杂度是线性的O(n)
For example, given:
s:
"barfoothefoobarman"
words:
["foo", "bar"]
You should return the indices:
[0,9].
(order does not matter).
思路: 判断一个值是否包含在一个数组中,首先应该想到将这个数组中的元素放入HashTable,否则每次查找都需要O(n)的时间复杂度。
时间复杂度:O(n*size),其中n为s的长度,size是指数组words包含多少个元素。当words元素不多的时候,我们可以说时间复杂度是线性的O(n)
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { size = words.size(); sLen = s.length(); wLen = words[0].length(); wordsLen = wLen * size; for(i = 0; i < size; i++){ word_counter[words[i]]++; } i = 0; while(i+wordsLen<=sLen){ for(j = 0; j < size; j++){ cmpStr = s.substr(i+j*wLen, wLen); if(word_counter.find(cmpStr)==word_counter.end()){ //不在words中,不符合 break; } counting[cmpStr]++; if(counting[cmpStr]>word_counter[cmpStr]){ //出现的次数多过words中的次数,不符合 break; } } if(j==size){//找到了一个符合的结果 ret.push_back(i); } counting.clear(); i++; } return ret; } private: string cmpStr; vector<int> ret; map<string,int> word_counter; map<string,int> counting; int size; //number of words int sLen; int wLen; int wordsLen; int i; int j; };
相关文章推荐
- 剖析touch事件在View中的传递
- gnome3
- Win2008 R2中IIS7.5配置完网站权限不足问题的解决方法
- 23设计模式之工厂方法(FactoryMethod)
- 使用VS2015编译openssl1.0.1p
- 杭州出租车改革:“破冰”后期待最终破题
- Access, SQL Server, Oracle, MySQL的区别与相似
- OpenCV图像的基础叠加
- ubuntu安装配置jdk1.7
- 读书笔记之《程序员的自我修养——链接、装载与库》
- 基于JQuery实现仿网易邮箱全屏动感滚动插件fullPage
- javascript 一次开发,多平台运行
- LeetCode 5 Longest Palindromic Substring(最大回文子字符串)
- SSO单点登录
- Python 类 --基础与要点
- MVC 异步请求
- vim中同时打开多个文件 同时显示多个窗口
- MySQL数据库
- 在PPT2007中制作礼花绽放动画效果ppt模板打包下载
- python获取对象信息type、dir、getattr、setattr