【Substring with Concatenation of All Words】cpp
题目:
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).
代码:
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> ret;
if ( words.empty() || s.empty() ) return ret;
const int len_w = words[].size(); // length of substring in words
const int end = words.size()*len_w; // total length of words
if ( end>s.size() ) return ret; // s size not enough
map<string, int> ori;
for ( int i=; i<words.size(); ++i )
{
if ( ori.find(words[i])==ori.end() ){
ori[words[i]] = ;
}
else{
ori[words[i]]++;
}
}
map<string, int> found;
int match_num = ;
int begin = ;
int i = ;
while ( i<s.size() )
{
//cout << "i:" << i << endl;
//cout << "m:" << match_num << endl;
//cout << "begin:" << begin << endl;
// match one substring in words
if ( ori.find(s.substr(i,len_w))!=ori.end() )
{
found[s.substr(i,len_w)]++;
// substring occur more than times in words
if ( found[s.substr(i,len_w)]>ori[s.substr(i,len_w)] )
{
found.clear();
match_num = ;
begin++;
i=begin;
continue;
}
i = i+len_w;
match_num++;
//cout << match_num << endl;
// match all substrings in words and push back a starting indices
if ( match_num==words.size() )
{
ret.push_back(i-end);
found.clear();
begin++;
i = begin;
match_num=;
}
}
// not match
else
{
found.clear();
match_num = ;
begin++;
i=begin;
}
}
return ret;
}
};
tips:
采用双指针技巧。
维护几个关键变量:
1. begin:可能的有效开始位置
2. match_num: 已经匹配上的words中的个数
3. ori: words中每个string,及其出现的次数
4. found: 当前已匹配的interval中,words中每个string,及其出现的次数
思路就是如果找到了匹配的某个string,i就不断向后跳;跳的过程中可能有两种情况不能跳了:
a) 下一个固定长度的子字符串不匹配了
b) 下一个固定长度的子字符串虽然匹配上了words中的一个,但是匹配的数量已经超过了ori中该string的数量
如果一旦不能跳了,就要把match_num和found归零;而且需要回溯到begin++的位置,开始新一轮的搜寻。
这里有个细节要注意:
直接用found.clear()就可以了,如果一个一个清零,会超时。
======================================
第二次过这道题,代码简洁了,一些细节回忆着也写出来了。保留一个ori用于判断的,再维护一个wordHit用于计数的;ori不能动,wordHit每次clear后默认的value=0。
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> ret;
if ( words.empty() ) return ret;
int len = words[].size();
if ( len*words.size()>s.size() ) return ret;
map<string, int> wordHit;
map<string ,int> ori;
for ( int i=; i<words.size(); ++i ) ori[words[i]]++;
for ( int i=; i<=s.size()-len*words.size(); ++i )
{
wordHit.clear();
int j = i;
int hitCouts = ;
while ( hitCouts<words.size() && j<=s.size()-len )
{
// find word and not hit already
if ( ori.find(s.substr(j,len))==ori.end() ) break;
if ( wordHit[s.substr(j,len)]<ori[s.substr(j,len)] )
{
wordHit[s.substr(j,len)]++;
j += len;
hitCouts++;
}
else { break; }
}
// if hits all words
if ( hitCouts==words.size() ) ret.push_back(i);
}
return ret;
}
};
【Substring with Concatenation of All Words】cpp的更多相关文章
- 【Flatten Binary Tree to Linked List】cpp
题目: Given a binary tree, flatten it to a linked list in-place. For example,Given 1 / \ 2 5 / \ \ 3 4 ...
- 【Binary Tree Zigzag Level Order Traversal】cpp
题目: Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from lef ...
- 【Binary Tree Level Order Traversal II 】cpp
题目: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from ...
- 【Kth Smallest Element in a BST 】cpp
题目: Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. ...
- 【Search in Rotated Sorted Array II 】cpp
题目: Follow up for "Search in Rotated Sorted Array":What if duplicates are allowed? Would t ...
- 【Letter Combinations of a Phone Number】cpp
题目: Given a digit string, return all possible letter combinations that the number could represent. A ...
- 【Remove Duplicates from Sorted List II 】cpp
题目: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct ...
- 【Remove Duplicates from Sorted Array II】cpp
题目: Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For ex ...
- 【leetcode】Substring with Concatenation of All Words
Substring with Concatenation of All Words You are given a string, S, and a list of words, L, that ar ...
随机推荐
- Altium_Designer如何快速寻找元件和封装
初学Altium碰到最多的问题就是:不知道元件放在哪个库中.这里我收集了DXP2004常用元件库下常见的元件.使用时,只需在libary中选择相应元件库后,输入英文的前几个字母就可看到相应的元件了.通 ...
- while循环小例
# 使用while 循环输入 1 2 3 4 5 6 8 9 10 n = 1 while n <= 10: if n == 7: pass else: print(n) n = n + 1 # ...
- IOS SVN源代码管理工具使用
01. 源代码管理工具概述(PPT)===================================================* 源代码管理工具的作用:# 能追踪一个项目从诞生一直到 ...
- java对字符串进行加密和解密(以下是来自其他博主)
背景:需要对读取数据库配置的文件进行加密,防止他人拿到数据,而对自己的代码,有要实现进行解密,网上给的加密方式,什么MD5,base64,还有等等,都太复杂,而且有些是单向的,只加密不解密,以下代码, ...
- 使用extentreports美化testng报告2,增加监听
有兴趣研究了extentreports报告美化插件,但是因为发现插件有很多内容不能自定义,所以放弃了这个插件,我扩充了官方代码的demo,在testng中增加了监听,并打印了一些测试用例,现在我把两个 ...
- mysql的慢查询实战+sql优化
背景:使用A电脑安装mysql,B电脑通过xshell方式连接,数据内容我都已经创建好,现在我已正常的进入到mysql中 步骤1:设置慢查询日志的超时时间,先查看日志存放路径查询慢日志的地址,因为有慢 ...
- hdu-3449 Consumer---有依赖性质的背包
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=3449 题目大意: fj打算去买一些东西,在那之前,他需要一些盒子去装他打算要买的不同的物品.每一个盒 ...
- 搭建FTP服务
(一)FTP服务概述 FTP服务概述:名称.功能.特点.端口 VSFTP:very secure FTP 端口:21 服务安装#yum install vsftpd lftp -y ##lftp ...
- 【BZOJ3506】[CQOI2014] 排序机械臂(Splay)
点此看题面 大致题意: 给你\(n\)个数.第一次找到最小值所在位置\(P_1\),翻转\([1,P_1]\),第二次找到剩余数中最小值所在位置\(P_2\),翻转\([2,P_2]\),以此类推.求 ...
- querystring处理参数小利器
相信上一章的讲解,相信大家对url地址有一个更直观的认识,在url解析的时候可以用querystring这样一个module替换,然后对这个query集成一个对象,这里不管是前端开发还是后端开发,都常 ...