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] 438. Find All Anagrams in a String 找出字符串中所有的变位词的更多相关文章

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

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

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

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

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

  4. LeetCode 438. 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 ...

  5. [leetcode]438. 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 ...

  6. [LeetCode] Find All Numbers Disappeared in an Array 找出数组中所有消失的数字

    Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and ot ...

  7. 10.Find All Anagrams in a String(在一个字符串中发现所有的目标串排列)

    Level:   Easy 题目描述: Given a string s and a non-empty string p, find all the start indices of p's ana ...

  8. 438. Find All Anagrams in a String - LeetCode

    Question 438. Find All Anagrams in a String Solution 题目大意:给两个字符串,s和p,求p在s中出现的位置,p串中的字符无序,ab=ba 思路:起初 ...

  9. 【leetcode】438. Find All Anagrams in a String

    problem 438. Find All Anagrams in a String solution1: class Solution { public: vector<int> fin ...

随机推荐

  1. Python 线程池(小节)

    Python 线程池(小节) from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor import os,time, ...

  2. Servlet中实现多个功能案例

    如何实现一个Servlet中的多个功能 前言:唉,打脸了,前脚刚说过要跟Servlet正式告别,后脚这不又来了,哈哈,总结出一点东西,纠结了一下还是做个分享吧,学习知识比面子重要,对吧,下回再也不约S ...

  3. Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'jdbc.username' in string value "${jdbc.username}"

    1.启动dubbo的引用dubbo服务时候报下面这个错误,这是由于去找dubbo的发布服务未找到报的错误,所以先启动dubbo的发布服务即可. [INFO] Scanning for projects ...

  4. C#: 解决Fody is only supported on MSBuild 16 and above

    背景信息: 使用Costura.Fody插件将自己写的程序打包成一个可以独立运行的EXE文件我们在开发程序的时候会引用很多DLL文件,在程序完成编写后,如果不把这些引用的DLL打包,在拷贝给到别人使用 ...

  5. 腾讯云-ASP.NET Core+Mysql+Jexus+CDN上云实践

    腾讯云-ASP.NET Core+Mysql+Jexus+CDN上云实践.md 开通腾讯云服务器和Mysql 知识点: ASP.NET Core和 Entity Framework Core的使用 L ...

  6. CSS 基础面试题

    1 介绍一下标准的CSS的盒子模型?与低版本IE的盒子模型有什么不同的? 标准盒子模型:宽度=内容的宽度(content)+ border + padding + margin 低版本IE盒子模型:宽 ...

  7. Java生鲜电商平台-电商促销业务分析设计与系统架构

    Java生鲜电商平台-电商促销业务分析设计与系统架构 说明:Java开源生鲜电商平台-电商促销业务分析设计与系统架构,列举的是常见的促销场景与源代码下载 左侧为享受促销的资格,常见为这三种: 首单 大 ...

  8. Spring框架完全掌握(上)

    引言 前面我写了一篇关于Spring的快速入门,旨在帮助大家能够快速地了解和使用Spring.既然是快速入门,讲解的肯定只是一些比较泛的知识,那么对于Spring的一些深入内容,我决定将其分为上.下两 ...

  9. 深度解析.NetFrameWork/CLR/C# 以及C#6/C#7新语法

    一:什么是.NetFrameWork/ CLR / C# 1:.NetFramework即架构,它是一个语言开发软件,提供了软件开发的框架,使开发更具工程性.简便性和稳定性,这个框架主要是针对于c#语 ...

  10. js中对字符串(String)去除空格

    str为要去除空格的字符串: 去除所有空格: str = str.replace(/\s+/g,""); 去除两头空格: str = str.replace(/^\s+|\s+$/ ...