题目链接: https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/

题目描述:

给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。

注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。

示例:

示例 1:

输入:
s = "barfoothefoobarman",
words = ["foo","bar"]
输出:[0,9]
解释:
从索引 0 和 9 开始的子串分别是 "barfoor" 和 "foobar" 。
输出的顺序不重要, [9,0] 也是有效答案。

示例 2:

输入:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
输出:[]

思路:

一开始,我的想法是,每次从s截取一定长度(固定的)的字符串,看这段字符串出现单词个数是否和要匹配的单词个数相等!如下代码:

class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
from collections import Counter
if not s or not words:return []
all_len = sum(map(len, words))
n = len(s)
words = Counter(words)
res = []
for i in range(0, n - all_len + 1):
tmp = s[i:i+all_len]
flag = True
for key in words:
if words[key] != tmp.count(key):
flag = False
break
if flag:res.append(i)
return res

但是比如: s = "ababaab" ,words = ["ab","ba","ba"]就会报错!

错误原因,因为计算时候我们会从字符串中间计算,也就是说会出现单词截断的问题.

所以我想另一种方法,

思路一:

因为单词长度固定的,我们可以计算出截取字符串的单词个数是否和words里相等,所以我们可以借用哈希表.

一个是哈希表是words,一个哈希表是截取的字符串,

比较两个哈希是否相等!

因为遍历和比较都是线性的,所以时间复杂度 :\(O(n^2)\)


上面思路每次都要反复遍历s;

下面介绍滑动窗口.

思路二:

滑动窗口!

我们一直在s维护着所有单词长度总和的一个长度队列!

关于滑动窗口,可以看看这篇文章.

时间复杂度:\(O(n)\)

还可以再优化,只是加一些判断,详细看代码吧!


关注我的知乎专栏,了解更多的解题技巧,大家一起进步,加油!

代码:

思路一:

python

class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
from collections import Counter
if not s or not words:return []
one_word = len(words[0])
all_len = len(words) * one_word
n = len(s)
words = Counter(words)
res = []
for i in range(0, n - all_len + 1):
tmp = s[i:i+all_len]
c_tmp = []
for j in range(0, all_len, one_word):
c_tmp.append(tmp[j:j+one_word])
if Counter(c_tmp) == words:
res.append(i)
return res

java

class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> res = new ArrayList<>();
if (s == null || s.length() == 0 || words == null || words.length == 0) return res;
HashMap<String, Integer> map = new HashMap<>();
int one_word = words[0].length();
int word_num = words.length;
int all_len = one_word * word_num;
for (String word : words) {
map.put(word, map.getOrDefault(word, 0) + 1);
}
for (int i = 0; i < s.length() - all_len + 1; i++) {
String tmp = s.substring(i, i + all_len);
HashMap<String, Integer> tmp_map = new HashMap<>();
for (int j = 0; j < all_len; j += one_word) {
String w = tmp.substring(j, j + one_word);
tmp_map.put(w, tmp_map.getOrDefault(w, 0) + 1);
}
if (map.equals(tmp_map)) res.add(i);
}
return res;
}
}

思路二:

python

class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
from collections import Counter
if not s or not words:return []
one_word = len(words[0])
word_num = len(words)
n = len(s)
words = Counter(words)
res = []
for i in range(0, one_word):
cur_cnt = 0
left = i
right = i
cur_Counter = Counter()
while right + one_word <= n:
w = s[right:right + one_word]
right += one_word
cur_Counter[w] += 1
cur_cnt += 1
while cur_Counter[w] > words[w]:
left_w = s[left:left+one_word]
left += one_word
cur_Counter[left_w] -= 1
cur_cnt -= 1
if cur_cnt == word_num :
res.append(left)
return res

java

class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> res = new ArrayList<>();
if (s == null || s.length() == 0 || words == null || words.length == 0) return res;
HashMap<String, Integer> map = new HashMap<>();
int one_word = words[0].length();
int word_num = words.length;
int all_len = one_word * word_num;
for (String word : words) {
map.put(word, map.getOrDefault(word, 0) + 1);
}
for (int i = 0; i < one_word; i++) {
int left = i, right = i, count = 0;
HashMap<String, Integer> tmp_map = new HashMap<>();
while (right + one_word <= s.length()) {
String w = s.substring(right, right + one_word);
tmp_map.put(w, tmp_map.getOrDefault(w, 0) + 1);
right += one_word;
count++;
while (tmp_map.getOrDefault(w, 0) > map.getOrDefault(w, 0)) {
String t_w = s.substring(left, left + one_word);
count--;
tmp_map.put(t_w, tmp_map.getOrDefault(t_w, 0) - 1);
left += one_word;
}
if (count == word_num) res.add(left); }
} return res;
}
}

再优化:

python

class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
from collections import Counter
if not s or not words:return []
one_word = len(words[0])
word_num = len(words)
n = len(s)
if n < one_word:return []
words = Counter(words)
res = []
for i in range(0, one_word):
cur_cnt = 0
left = i
right = i
cur_Counter = Counter()
while right + one_word <= n:
w = s[right:right + one_word]
right += one_word
if w not in words:
left = right
cur_Counter.clear()
cur_cnt = 0
else:
cur_Counter[w] += 1
cur_cnt += 1
while cur_Counter[w] > words[w]:
left_w = s[left:left+one_word]
left += one_word
cur_Counter[left_w] -= 1
cur_cnt -= 1
if cur_cnt == word_num :
res.append(left)
return res

java

class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> res = new ArrayList<>();
if (s == null || s.length() == 0 || words == null || words.length == 0) return res;
HashMap<String, Integer> map = new HashMap<>();
int one_word = words[0].length();
int word_num = words.length;
int all_len = one_word * word_num;
for (String word : words) {
map.put(word, map.getOrDefault(word, 0) + 1);
}
for (int i = 0; i < one_word; i++) {
int left = i, right = i, count = 0;
HashMap<String, Integer> tmp_map = new HashMap<>();
while (right + one_word <= s.length()) {
String w = s.substring(right, right + one_word);
right += one_word;
if (!map.containsKey(w)) {
count = 0;
left = right;
tmp_map.clear();
} else {
tmp_map.put(w, tmp_map.getOrDefault(w, 0) + 1);
count++;
while (tmp_map.getOrDefault(w, 0) > map.getOrDefault(w, 0)) {
String t_w = s.substring(left, left + one_word);
count--;
tmp_map.put(t_w, tmp_map.getOrDefault(t_w, 0) - 1);
left += one_word;
}
if (count == word_num) res.add(left);
}
}
}
return res;
}
}

[LeetCode] 30. 串联所有单词的子串的更多相关文章

  1. Java实现 LeetCode 30 串联所有单词的子串

    30. 串联所有单词的子串 给定一个字符串 s 和一些长度相同的单词 words.找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置. 注意子串要与 words 中的单词完全匹配, ...

  2. Leetcode 30 串联所有单词的子串 滑动窗口+map

    见注释.滑动窗口还是好用. class Solution { public: vector<int> findSubstring(string s, vector<string> ...

  3. [LeetCode] 30. 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 sta ...

  4. [LeetCode] 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 sta ...

  5. 【LeetCode-面试算法经典-Java实现】【030-Substring with Concatenation of All Words(串联全部单词的子串)】

    [030-Substring with Concatenation of All Words(串联全部单词的子串)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Yo ...

  6. Leetcode 30.与所有单词相关联的子串

    与所有单词相关联的字串 给定一个字符串 s 和一些长度相同的单词 words.在 s 中找出可以恰好串联 words 中所有单词的子串的起始位置. 注意子串要与 words 中的单词完全匹配,中间不能 ...

  7. [leetcode] 30. 与所有单词相关联的字串(cn第653位做出此题的人~)

    30. 与所有单词相关联的字串 这个题做了大概两个小时左右把...严重怀疑leetcode的judge机器有问题.同样的代码交出来不同的运行时长,能不能A题还得看运气? 大致思路是,给words生成一 ...

  8. Leetcode——30.与所有单词相关联的字串【##】

    @author: ZZQ @software: PyCharm @file: leetcode30_findSubstring.py @time: 2018/11/20 19:14 题目要求: 给定一 ...

  9. 【LeetCode 30】串联所有单词的子串

    题目链接 [题解] 开个字典树记录下所有的单词. 然后注意题目的已知条件 每个单词的长度都是一样的. 这就说明不会出现某个字符串是另外一个字符串的前缀的情况(除非相同). 所以可以贪心地匹配(遇到什么 ...

随机推荐

  1. Golang入门及开发环境配置

    Go语言诞生背景 计算机硬件更新频繁,主流编程语言无法发挥多核多CPU的性能 软件系统复杂度不断变高,缺乏简洁高效的编程语言 C/C++运行速度快,但编译速度慢 Go语言特点 静态类型开发语言 静态: ...

  2. LTM加速优化特性

    TCP Express TCP Express 是 LTM 产品的一项重要特性. 借助 TCP Express,LTM 可分别为客户机端和服务器端创建独立的连接.这样一来,LTM 可以针对客户机连接和 ...

  3. 观察者模式------《Head First 设计模式》

    第二章---观察者模式 xzmxddx 学习方式:书籍<Head First 设计模式>,这本书通俗易懂,所有知识点全部取自本书. 面向对象设计原则 封装变化 多用组合,少用继承 针对接口 ...

  4. sublime安装完插件后出现的一些问题

    1.安装anaconda后代码前面出现小方框 解决办法:这是由于不符合PEP8代码规范,在空白地方右击,选择anaconda --> autoformat PEP8 Errors ,同时保证导入 ...

  5. StringTokenizer工具类的使用

    package stringtokenizer.java; import java.util.StringTokenizer; public class stringtokenizer { publi ...

  6. Jprofiler远程监控JVM

    一.下载并安装 本地和远程服务器分别安装Jprofiler,下载地址 二.Windows远程连接JVM配置 1.打开Windows客户端Jprofiler 2.点Cancel 3.创建远程会话 4.添 ...

  7. 浅谈javaweb三大框架和MVC设计模式

    一.MVC设计模式 1.MVC的概念 首先我们需要知道MVC模式并不是javaweb项目中独有的,MVC是一种软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model).视图(Vie ...

  8. CentOS关闭系统不必要的端口

    注:以下所有操作均在CentOS 7.2 x86_64位系统下完成. 1)首先查看当前系统开放的端口号: # netstat -tlnup Active Internet connections (o ...

  9. 2017-03-04 idea破解

    https://blog.csdn.net/qq_27686779/article/details/78870816 防止原址被删除,备份下,亲测可用 http://idea.java.sx/ 简单快 ...

  10. Vue知识整理12:事件绑定

    采用v-on命令进行事件的绑定操作,通过单击按钮,实现按钮文字上数值的增加 带参数的事件过程 可以添加$event事件,实现事件信息的获取