Substring with Concatenation of All Words
2015-12-03 23:56
232 查看
题目: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).
思路:
定义两个hash表,一个就是传统的把所有的输入进去,对应代号。本题的一个技巧就是每次从一个位置开始判断,然后再最外面写一个从当前位置判断再这个 start 能否成功的函数:
函数的技巧就是从start位置截取每一个单词的长度,比对是否出现过,出现的次数不能超过1次。
代码:
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { vector<int> res; if(words.empty()) return res; int wordSize=words[0].size(); int totalWords=words.size(); int totalLen=wordSize*totalWords; if(s.size()<totalLen) return res; unordered_map<string,int>wordCount; for(int i=0;i<totalWords;i++){ wordCount[words[i]]++; } for(int i=0;i<=s.size()-totalLen;i++){ if(checkSubstring( s,i, wordCount, wordSize, totalWords)) res.push_back(i); } return res; } bool checkSubstring(string &s,int start,unordered_map<string,int>&wordCount,int wordSize,int totalWords){ if(s.size()-start+1<wordSize*totalWords) return false; unordered_map<string,int>wordFound; for(int i=0;i<totalWords;i++){ string tmp=s.substr(start+i*wordSize,wordSize); if(wordCount[tmp]==0) return false; wordFound[tmp]++; if(wordFound[tmp]>wordCount[tmp]) return false; } return true; } };
相关文章推荐
- 欢迎使用CSDN-markdown编辑器
- 黑马程序员__Java接口定义
- StatePattern-HeadFirst学习
- Windows 7 & Windows 8 简体中文旗舰版下载地址
- with管理文件操作
- WebKit之JS内嵌C++对象
- iOS 网络与多线程--3.异步Get方式的网络请求(非阻塞)
- IntelliJ IDEA 进行js Debug调试
- 二叉搜索树 HDU 3791
- 显示一个文件的某几行
- 实验三 进程调度模拟实验
- _______________ 字符串分隔符_______------------------------
- Fragment的两个子类ListFragment和DialogFragment的应用Demo
- 全排列POJ1256Anagram
- 我曾经做过的插件
- Xcode常用快捷键
- win8笔记本无法搜索wifi信号找不到WLAN该 wifi共享特别注意的服务
- 说说为什么阿里要破冰?
- poj2387(最简单的最短路)
- 高性能IO模型浅析