题目:

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的更多相关文章

  1. 【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 ...

  2. 【Binary Tree Zigzag Level Order Traversal】cpp

    题目: Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from lef ...

  3. 【Binary Tree Level Order Traversal II 】cpp

    题目: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from ...

  4. 【Kth Smallest Element in a BST 】cpp

    题目: Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. ...

  5. 【Search in Rotated Sorted Array II 】cpp

    题目: Follow up for "Search in Rotated Sorted Array":What if duplicates are allowed? Would t ...

  6. 【Letter Combinations of a Phone Number】cpp

    题目: Given a digit string, return all possible letter combinations that the number could represent. A ...

  7. 【Remove Duplicates from Sorted List II 】cpp

    题目: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct  ...

  8. 【Remove Duplicates from Sorted Array II】cpp

    题目: Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For ex ...

  9. 【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 ...

随机推荐

  1. 2019.03.14 ZJOI2019模拟赛 解题报告

    得分: \(100+100+0=200\)(\(T1\)在最后\(2\)分钟写了出来,\(T2\)在最后\(10\)分钟写了出来,反而\(T3\)写了\(4\)个小时爆\(0\)) \(T1\):风王 ...

  2. 转:spring mvc返回json数据格式

    转:http://www.cnblogs.com/ssslinppp/p/4675495.html <Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: ...

  3. HTML5 input date 移动端 IOS 不支持问题

    1.placeholder 问题解决方法 对 input type date 使用 placeholder 的目的是为了让用户更准确的输入日期格式,iOS 上会有 date 不会显示 placehol ...

  4. multi-view datasets

    http://rll.berkeley.edu/2014_ICRA_dataset/ http://rgbd-dataset.cs.washington.edu/dataset/

  5. Android 最新学习资料收集

    收集这份资料的灵感来源于我的浏览器收藏夹快爆了,后来在github 上也看到了很优秀的开源库的收集资料,非常的好,但是太过于多,也不够新,所以决定自己来做一个.原始的markdowm文件已经放到git ...

  6. lintcode_93_平衡二叉树

    平衡二叉树   描述 笔记 数据 评测 给定一个二叉树,确定它是高度平衡的.对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1. 您在真实的面试中是否遇到过 ...

  7. Spring MVC 接收前端参数的方式

    方式一: 普通方式接收 1 @RequestMapping("/index") 2 public String getUserName(String username) { 3 S ...

  8. Linux下Mysql5.6 二进制安装

    1.1下载二进制安装包 wget https://dev.mysql.com/get/Downloads/MySQL-5.6/mysql-5.6.40-linux-glibc2.12-x86_64.t ...

  9. PHP siege 压测 QPS大小

    1.使用 PHP-FPM SOCKET的形式通讯 2.配置 PHP-FPM配置 [root@bogon php-fpm.d]# ls -al 总用量 drwxr-xr-x. root root 8月 ...

  10. 【vlan-端口配置】

    搭建好拓扑图如下: 分别配置两台终端的ip地址 创建vlan把e0/4/0接口加入到新的vlan中 连通性失败 . 同理在把e0/4/1加入到vlan视图中 连通性成功 : 搭建好拓扑图如下 进入e0 ...