[LeetCode] Find All Anagrams in a String 找出字符串中所有的变位词

时间:2022-03-19 15:01:13

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:

Input:
s: "cbaebabacd" p: "abc" Output:
[0, 6] Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

Example 2:

Input:
s: "abab" p: "ab" Output:
[0, 1, 2] Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

这道题给了我们两个字符串s和p,让在s中找字符串p的所有变位次的位置,所谓变位次就是字符种类个数均相同但是顺序可以不同的两个词,那么肯定首先就要统计字符串p中字符出现的次数,然后从s的开头开始,每次找p字符串长度个字符,来验证字符个数是否相同,如果不相同出现了直接 break,如果一直都相同了,则将起始位置加入结果 res 中,参见代码如下:

解法一:

class Solution {
public:
vector<int> findAnagrams(string s, string p) {
if (s.empty()) return {};
vector<int> res, cnt(, );
int ns = s.size(), np = p.size(), i = ;
for (char c : p) ++cnt[c];
while (i < ns) {
bool success = true;
vector<int> tmp = cnt;
for (int j = i; j < i + np; ++j) {
if (--tmp[s[j]] < ) {
success = false;
break;
}
}
if (success) {
res.push_back(i);
}
++i;
}
return res;
}
};

我们可以将上述代码写的更加简洁一些,用两个哈希表,分别记录p的字符个数,和s中前p字符串长度的字符个数,然后比较,如果两者相同,则将0加入结果 res 中,然后开始遍历s中剩余的字符,每次右边加入一个新的字符,然后去掉左边的一个旧的字符,每次再比较两个哈希表是否相同即可,参见代码如下:

解法二:

class Solution {
public:
vector<int> findAnagrams(string s, string p) {
if (s.empty()) return {};
vector<int> res, m1(, ), m2(, );
for (int i = ; i < p.size(); ++i) {
++m1[s[i]]; ++m2[p[i]];
}
if (m1 == m2) res.push_back();
for (int i = p.size(); i < s.size(); ++i) {
++m1[s[i]];
--m1[s[i - p.size()]];
if (m1 == m2) res.push_back(i - p.size() + );
}
return res;
}
};

下面这种利用滑动窗口 Sliding Window 的方法也比较巧妙,首先统计字符串p的字符个数,然后用两个变量 left 和 right 表示滑动窗口的左右边界,用变量 cnt 表示字符串p中需要匹配的字符个数,然后开始循环,如果右边界的字符已经在哈希表中了,说明该字符在p中有出现,则 cnt 自减1,然后哈希表中该字符个数自减1,右边界自加1,如果此时 cnt 减为0了,说明p中的字符都匹配上了,那么将此时左边界加入结果 res 中。如果此时 right 和 left 的差为p的长度,说明此时应该去掉最左边的一个字符,如果该字符在哈希表中的个数大于等于0,说明该字符是p中的字符,为啥呢,因为上面有让每个字符自减1,如果不是p中的字符,那么在哈希表中个数应该为0,自减1后就为 -1,所以这样就知道该字符是否属于p,如果去掉了属于p的一个字符,cnt 自增1,参见代码如下:

解法三:

class Solution {
public:
vector<int> findAnagrams(string s, string p) {
if (s.empty()) return {};
vector<int> res, m(, );
int left = , right = , cnt = p.size(), n = s.size();
for (char c : p) ++m[c];
while (right < n) {
if (m[s[right++]]-- >= ) --cnt;
if (cnt == ) res.push_back(left);
if (right - left == p.size() && m[s[left++]]++ >= ) ++cnt;
}
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/438

类似题目:

Valid Anagram

Anagrams

参考资料:

https://leetcode.com/problems/find-all-anagrams-in-a-string/

https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92015/ShortestConcise-JAVA-O(n)-Sliding-Window-Solution

https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92027/c-on-sliding-window-concise-solution-with-explanation

https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92007/Sliding-Window-algorithm-template-to-solve-all-the-Leetcode-substring-search-problem.

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Find All Anagrams in a String 找出字符串中所有的变位词的更多相关文章

  1. &lbrack;LeetCode&rsqb; 438&period; Find All Anagrams in a String 找出字符串中所有的变位词

    Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings ...

  2. 【easy】438&period;Find All Anagrams in a String 找出字符串中所有的变位词

    Input: s: "abab" p: "ab" Output: [0, 1, 2] Explanation: The substring with start ...

  3. 438 Find All Anagrams in a String 找出字符串中所有的变位词

    详见:https://leetcode.com/problems/find-all-anagrams-in-a-string/description/ C++: class Solution { pu ...

  4. &lbrack;LeetCode&rsqb; 186&period; Reverse Words in a String II 翻转字符串中的单词 II

    Given an input string, reverse the string word by word. A word is defined as a sequence of non-space ...

  5. &lbrack;LeetCode&rsqb; 557&period; Reverse Words in a String III 翻转字符串中的单词 III

    Given a string, you need to reverse the order of characters in each word within a sentence while sti ...

  6. 剑指Offer 找出字符串中第一个只出现一次的字符

    题目描述 找出字符串中第一个只出现一次的字符 如果无此字符 请输出'.' 输入描述: 输入一串字符,由小写字母组成 输出描述: 输出一个字符 输入例子: asdfasdfo 输出例子: o 思路:数组 ...

  7. 找出字符串中第一个不重复的字符&lpar;JavaScript实现&rpar;

    如题~ 此算法仅供参考,小菜基本不懂高深的算法,只能用最朴实的思想去表达. //找出字符串中第一个不重复的字符 // firstUniqueChar("vdctdvc"); --& ...

  8. &lbrack;leetcode&sol;lintcode 题解&rsqb; 谷歌面试题:找出有向图中的弱连通分量

    请找出有向图中弱连通分量.图中的每个节点包含 1 个标签和1 个相邻节点列表.(有向图的弱连通分量是任意两点均有有向边相连的极大子图) 将连通分量内的元素升序排列. 在线评测地址:https://ww ...

  9. LeetCode 438&period; Find All Anagrams in a String (在字符串中找到所有的变位词)

    Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings ...

随机推荐

  1. Netty5使用自签证书实现SSL安全连接

    这次使用的Netty是最新的5.0 Alpha2版本,下载地址是:http://dl.bintray.com/netty/downloads/netty-5.0.0.Alpha2.tar.bz2,发布 ...

  2. python select

    server #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: zengchunyun " ...

  3. 转:Qt 嵌入式开发环境搭建

    地址: http://www.cnblogs.com/lishixian/articles/3013897.html         作者:lsx_007 这里主要是记录了自己在搭建嵌入式开发环境时阅 ...

  4. 201521123023《Java程序设计》第8周学习总结

    1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结集合与泛型相关内容. 1.2 选做:收集你认为有用的代码片段 2. 书面作业 本次作业题集集合 1.List中指定元素的删除(题目4 ...

  5. shc &amp&semi; unshc 安装

    shc & unshc 安装 shc 安装 git clone https://github.com/neurobin/shc.git cd shc ./configure make &amp ...

  6. 全网最详细的基于Ubuntu14&period;04&sol;16&period;04 &plus; Anaconda2 &sol; Anaconda3 &plus; Python2&period;7&sol;3&period;4&sol;3&period;5&sol;3&period;6安装Tensorflow详细步骤(图文)(博主推荐)

    不多说,直接上干货! 前言 建议参照最新的tensorflow安装步骤(Linux,官方网站经常访问不是很稳定,所以给了一个github的地址):         https://github.com ...

  7. 使用golang的slice来模拟栈

    slice(切片):底层数据结构是数组 stack(栈):一种先进后出的数据结构 普通版的模拟写入和读取的栈 package main import "fmt" //栈的特点是先进 ...

  8. dict 知识汇总

    增: 1. copy 浅复制 2. setdefault (有就查询,没有就添加): 删: 3. clear:清除 4. pop :删除指定键值对 5. popitem :  随机删除一组键值对 改: ...

  9. 如何打jar包 学习笔记

    jar包是由.class文件压缩而成.要查看jar包中的内容,使用压缩工具 解压缩即可.也可以做修改,并重新打成jar包.总结一下最近学到的一些打jar包的方法: 一.DOS下使用jar命令 打jar ...

  10. Android中的缩略图加载-不浪费一点多余的内存

    1. Why,为什么要加载缩略图? 有的时候不需要展示原图,只需展示图片的缩略图,可以节省内存.比如:网易新闻中的图片浏览,左边展示的小狮子图片就是一个缩略图,点击这个图片,才会展示原图.   2. ...