[LeetCode]438. 找到字符串中所有字母异位词
Posted coding-gaga
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]438. 找到字符串中所有字母异位词相关的知识,希望对你有一定的参考价值。
题目
给定一个字符串?s?和一个非空字符串?p,找到?s?中所有是?p?的字母异位词的子串,返回这些子串的起始索引。
字符串只包含小写英文字母,并且字符串?s?和 p?的长度都不超过 20100。
说明:
字母异位词指字母相同,但排列不同的字符串。
不考虑答案输出的顺序。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-anagrams-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
代码
class Solution
public List<Integer> findAnagrams(String s, String p)
if(s==null||p==null)
return null;
List<Integer> ansList=new ArrayList<Integer>();
HashMap<Character,Integer> needs=new HashMap<>();
HashMap<Character,Integer> window=new HashMap<>();
for(int i=0;i<p.length();++i)
needs.put(p.charAt(i),needs.getOrDefault(p.charAt(i),0)+1);
int l=0;
int r=0;
int matchCnt=0;
int hopMatchCharCnt=needs.size();//
while(r<s.length())
char c=s.charAt(r);
if(needs.containsKey(c))
window.put(c,window.getOrDefault(c,0)+1);
if(window.get(c).equals(needs.get(c)))
++matchCnt;
while(matchCnt==hopMatchCharCnt)//
if(r-l+1==p.length())//
ansList.add(l);
//包含子串情况下l不断右移
char leftC=s.charAt(l);//
if(window.containsKey(leftC))
window.put(leftC,window.get(leftC)-1);//
if(window.get(leftC)<needs.get(leftC))
--matchCnt;
++l;
++r;
return ansList;
以上是关于[LeetCode]438. 找到字符串中所有字母异位词的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 438 找到字符串中所有字母异位词[数组 滑动窗口] HERODING的LeetCode之路
leetcode 438. 找到字符串中所有字母异位词(Find All Anagrams in a String)
LeetCode 438. 找到字符串中所有字母异位词 / 786. 第 K 个最小的素数分数 / 400. 第 N 位数字(优先队列,二分+双指针)