题目链接

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

算法1

暴力解法,从字符串s的每个位置都判断一次(如果从当前位置开始的子串长度小于L中所有单词长度,不用判断),从当前位置开始的子串的前段部分能不能由集合L里面的单词拼接而成。

从某一个位置 i 判断时,依次判断单词s[i,i+2], s[i+3,i+5], s[i+6, i+8]…是否在集合中,如果单词在集合中,就从集合中删除该单词。

我们用一个hash map来保存单词,这样可以在O(1)时间内判断单词是否在集合中

算法的时间复杂度是O(n*(l*k))n是字符串的长度,l是单词的个数,k是单词的长度

递归代码如下:

class Solution {
private:
int wordLen; public:
vector<int> findSubstring(string S, vector<string> &L) {
unordered_map<string, int>wordTimes;
for(int i = 0; i < L.size(); i++)
if(wordTimes.count(L[i]) == 0)
wordTimes.insert(make_pair(L[i], 1));
else wordTimes[L[i]]++;
wordLen = L[0].size(); vector<int> res;
for(int i = 0; i <= (int)(S.size()-L.size()*wordLen); i++)
if(helper(S, i, wordTimes, L.size()))
res.push_back(i);
return res;
} //判断子串s[index...]的前段是否能由L中的单词组合而成
bool helper(string &s, const int index,
unordered_map<string, int>&wordTimes, const int wordNum)
{
if(wordNum == 0)return true;
string firstWord = s.substr(index, wordLen);
unordered_map<string, int>::iterator ite = wordTimes.find(firstWord);
if(ite != wordTimes.end() && ite->second > 0)
{
(ite->second)--;
bool res = helper(s, index+wordLen, wordTimes, wordNum-1);
(ite->second)++;//恢复hash map的状态
return res;
}
else return false;
}
};

非递归代码如下:

class Solution {
private:
int wordLen; public:
vector<int> findSubstring(string S, vector<string> &L) {
unordered_map<string, int>wordTimes;
for(int i = 0; i < L.size(); i++)
if(wordTimes.count(L[i]) == 0)
wordTimes.insert(make_pair(L[i], 1));
else wordTimes[L[i]]++;
wordLen = L[0].size(); vector<int> res;
for(int i = 0; i <= (int)(S.size()-L.size()*wordLen); i++)
if(helper(S, i, wordTimes, L.size()))
res.push_back(i);
return res;
} //判断子串s[index...]的前段是否能由L中的单词组合而成
bool helper(const string &s, int index,
unordered_map<string, int>wordTimes, int wordNum)
{
for(int i = index; wordNum != 0 && i <= (int)s.size()-wordLen; i+=wordLen)
{
string word = s.substr(i, wordLen);
unordered_map<string, int>::iterator ite = wordTimes.find(word);
if(ite != wordTimes.end() && ite->second > 0)
{ite->second--; wordNum--;}
else return false;
}
if(wordNum == 0)return true;
else return false;
}
};

OJ递归的时间小于非递归时间,因为非递归的helper函数中,hash map参数是传值的方式,每次调用都要拷贝一次hash map,递归代码中一直只存在一个hash map对象


算法2

回想前面的题目:LeetCode:Longest Substring Without Repeating CharactersLeetCode:Minimum Window Substring ,都用了一种滑动窗口的方法。这一题也可以利用相同的思想。

比如s = “a1b2c3a1d4”L={“a1”,“b2”,“c3”,“d4”}

窗口最开始为空,

a1在L中,加入窗口 【a1】b2c3a1d4                            本文地址

b2在L中,加入窗口 【a1b2】c3a1d4

c3在L中,加入窗口 【a1b2c3】a1d4

a1在L中了,但是前面a1已经算了一次,此时只需要把窗口向右移动一个单词a1【b2c3a1】d4

d4在L中,加入窗口a1【b2c3a1d4】找到了一个匹配

如果把s改为“a1b2c3kka1d4”,那么在第四步中会碰到单词kk,kk不在L中,此时窗口起始位置移动到kk后面a1b2c3kk【a1d4

class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
unordered_map<string, int>wordTimes;//L中单词出现的次数
for(int i = 0; i < L.size(); i++)
if(wordTimes.count(L[i]) == 0)
wordTimes.insert(make_pair(L[i], 1));
else wordTimes[L[i]]++;
int wordLen = L[0].size(); vector<int> res;
for(int i = 0; i < wordLen; i++)
{//为了不遗漏从s的每一个位置开始的子串,第一层循环为单词的长度
unordered_map<string, int>wordTimes2;//当前窗口中单词出现的次数
int winStart = i, cnt = 0;//winStart为窗口起始位置,cnt为当前窗口中的单词数目
for(int winEnd = i; winEnd <= (int)S.size()-wordLen; winEnd+=wordLen)
{//窗口为[winStart,winEnd)
string word = S.substr(winEnd, wordLen);
if(wordTimes.find(word) != wordTimes.end())
{
if(wordTimes2.find(word) == wordTimes2.end())
wordTimes2[word] = 1;
else wordTimes2[word]++; if(wordTimes2[word] <= wordTimes[word])
cnt++;
else
{//当前的单词在L中,但是它已经在窗口中出现了相应的次数,不应该加入窗口
//此时,应该把窗口起始位置想左移动到,该单词第一次出现的位置的下一个单词位置
for(int k = winStart; ; k += wordLen)
{
string tmpstr = S.substr(k, wordLen);
wordTimes2[tmpstr]--;
if(tmpstr == word)
{
winStart = k + wordLen;
break;
}
cnt--;
}
} if(cnt == L.size())
res.push_back(winStart);
}
else
{//发现不在L中的单词
winStart = winEnd + wordLen;
wordTimes2.clear();
cnt = 0;
}
}
}
return res;
}
};

算法时间复杂度为O(n*k))n是字符串的长度,k是单词的长度

【版权声明】转载请注明出处http://www.cnblogs.com/TenosDoIt/p/3807055.html

LeetCode:Substring with Concatenation of All Words (summarize)的更多相关文章

  1. 【LeetCode】647. Palindromic Substrings 解题报告(Python)

    [LeetCode]647. Palindromic Substrings 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/p ...

  2. Leetcode之回溯法专题-78. 子集(Subsets)

    Leetcode之回溯法专题-78. 子集(Subsets) 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集). 说明:解集不能包含重复的子集. 示例: 输入: nums = ...

  3. Leetcode之回溯法专题-77. 组合(Combinations)

    Leetcode之回溯法专题-77. 组合(Combinations)   给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合. 示例: 输入: n = 4, k = 2 输 ...

  4. Leetcode之回溯法专题-46. 全排列(Permutations)

    Leetcode之回溯法专题-46. 全排列(Permutations) 给定一个没有重复数字的序列,返回其所有可能的全排列. 示例: 输入: [1,2,3] 输出: [ [1,2,3], [1,3, ...

  5. 【LeetCode】376. Wiggle Subsequence 解题报告(Python)

    [LeetCode]376. Wiggle Subsequence 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.c ...

  6. 【LeetCode】649. Dota2 Senate 解题报告(Python)

    [LeetCode]649. Dota2 Senate 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地 ...

  7. 【LeetCode】911. Online Election 解题报告(Python)

    [LeetCode]911. Online Election 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ ...

  8. 【LeetCode】886. Possible Bipartition 解题报告(Python)

    [LeetCode]886. Possible Bipartition 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu ...

  9. 【LeetCode】36. Valid Sudoku 解题报告(Python)

    [LeetCode]36. Valid Sudoku 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址 ...

随机推荐

  1. 。net 添加或获取文件关联

    文件关联设置 2011-02-07 14:25:36|  分类: VB.net2008或2010 |  标签:文件关联  |举报|字号 订阅     原理:以后缀名为.txt为例 方式一: 1.在注册 ...

  2. cocos2d-x之内存管理(4)

    c++的内存管理一直以来都是个问题,也有多种实现方案,比如智能指针,使用引用计数等,cocos2d-x也需要涉及到内存的管理. cocos2d-x是如何管理内存的呢? cocos2d-x的内存管理主要 ...

  3. 隐藏 input 标签的边框

    css input 如何去掉点击后出现的边框:css文件里加:*:focus { outline: none; } 或 input {outline:none;} 去边框的方法如下 方法1: < ...

  4. php错误级别的设置方法

    PHP在运行时, 针对严重程度不同的错误,会给以不同的提示. eg:在$a没声明时,直接相加,值为NULL,相加时当成0来算.但是,却提示NOTICE,即注意. 我们在开发中, 为了程序的规范性,把报 ...

  5. Linux tar打包命令

    Linux tar打包命令: 范例一:将整个 /etc 目录下的文件全部打包成为 /tmp/etc.tar [root@linux ~]# tar -cvf /tmp/etc.tar /etc < ...

  6. MySQL中distinct和group by性能比较[转]

    MySQL中distinct和group by性能比较[转] 之前看了网上的一些测试,感觉不是很准确,今天亲自测试了一番.得出了结论(仅在个人计算机上测试,可能不全面,仅供参考) 测试过程: 准备一张 ...

  7. mongoDB研究笔记:复制集数据同步机制

    http://www.cnblogs.com/guoyuanwei/p/3279572.html  概述了复制集,整体上对复制集有了个概念,但是复制集最重要的功能之一数据同步是如何实现的?带着这个问题 ...

  8. Linux下oracle11gR2系统安装到数据库建立配置及最后oracle的dmp文件导入一站式操作记录

    简介 之前也在linux下安装过oralce,可每次都是迷迷糊糊的,因为大脑一片空白,网上随便看见一个文档就直接复制,最后搞了乱七八糟,虽然装上了,却乱得很,现在记录下来,希望能给其他网上朋友遇到问题 ...

  9. MVC中用Jpaginate分页 So easy!(兼容ie家族)

    看过几款分页插件,觉得Jpaginate比较简约,样式也比较容易的定制,而且体验也比较好,支持鼠标滑动效果.先上效果图: 整个过程很简单,只需要3步 一.引入相关样式和脚本: 1.MVC4中,用了Bu ...

  10. Nim教程【一】

    这应该是国内第一个关于Nim入门的系列教程 什么是Nim 我们先来引述网友 Luikore的一段话: Nim 不是函数式的, 但 Nim 支持卫生宏, 可以做 AST 重写, 可以自定编译规则, 是静 ...