30.查找所有可能的字符串组合
2017-07-18 22:41
232 查看
Substring with Concatenation of All Words
问题描述:
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).
知识补充:
unordered_mapunordered_map<int, int> c;//<type,type>分别对应键的类型和键值的类型 c[0] = 1;//简单的插入数据形式 c.find(key)==c.end();//判断无序图内是否有这个键 c.count(key);//访问键值
测试代码:
vector<int> findSubstring(string s, vector<string>& words) { vector<int> result; unordered_map<string, int> c; unordered_map<string, int> n; int j,i,k; string ss; int l = words[0].length(); for (string word : words) c[word]++; for(i=0;i<s.length()-l*words.size()+1;i++) { j=i; k=words.size(); n = c; while(k) { ss = s.substr(j,l); if(n[ss]<1) { break; } if(n.find(ss)!=n.end()) { --n[ss]; j = j+l; k--; }else{ break; } } if(k==0) { result.push_back(i); } } return result; }
性能:
参考答案:
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { vector<int> ret; if(words.empty() || words[0].length()==0) return ret; int wl=words[0].length(); int len=wl*words.size(); int end=s.length()-len; if(end<0) return ret; unordered_map<string, int> dict; for(string word : words) dict[word]++; for(int st=0; st<wl; st++) { helper(ret, dict, s, words, st, end, wl, len); } return ret; } private: void helper(vector<int>& ret, unordered_map<string, int>& dict, string& s, vector<string>& words, int st, int end, int wl, int len) { unordered_map<string, int> hash; int left=st, right=st; while(left<=end) { string nxt=s.substr(right, wl); if(dict.count(nxt)==0) { left=right+wl; hash.clear(); } else { if(hash.count(nxt)==0) hash[nxt]=1; else if(hash[nxt]<dict[nxt]) hash[nxt]++; else { string rem=s.substr(left, wl); while(rem!=nxt) { hash[rem]--; left+=wl; rem=s.substr(left, wl); } left+=wl; } } right+=wl; if(right-left==len) ret.push_back(left); } } };
性能:
4000
相关文章推荐
- 查找和是某一值或者某一范围的的所有可能
- webshell下查找所有IIS站点配置(渗透时可能有点用)
- 假设某棵二叉查找树的所有键均为1到10的整数,现在我们要查找5。下面____不可能是键的检查序列。
- SQL SERVER中查找指定节点的所有子节点的示例函数
- Shell Script: 查找某个目录某个时间以后的所有文件
- 在所有存储过程中查找一个关键字
- DFS 对一系列给定数据 进行深度优先遍历 获得54321的所有可能组合
- Linq to xml 查找所有的子节点
- 在从池中获取连接之前超时时间已过。出现这种情况可能是因为所有池连接
- [置顶] 欢迎进入阿钟的博客导航——快速查找所有博客
- php手册里的 显示所有你查找的字符的位置,以及该字符所在的单词
- 线性时间查找一个图中的所有node-cut点分割
- C# 查找指定文件夹下 指定后缀名的所有文件(文件列表)
- 一个求24点所有可能解的VB源代码及程序实现
- 输入两个整数 n 和 m,从数列1,2,3.......n 中随意取几个数,使其和等于 m ,要求将其中所有的可能组合列出来.
- (PowerShell) 查找所有文件中的指定字符串
- DFS 遍历数组所有可能存在的出栈顺序
- Linux系统中 查找目录下的所有文件中是否含有某个字符串
- hibernate查找数据库中所有内容cannot be cast to com.shzy.model.Materia
- linux 批量替换文件内容及查找某目录下所有包含某字符串的文件(批量修改文件内容)