LeetCode 438 Find All Anagrams in a String解析

来源:互联网 发布:qq宠物 知乎 编辑:程序博客网 时间:2024/06/12 04:09

leetcode 438 解析

题目描述
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所有元素的子串的起始位置。
拟采用滑动窗口方法求解。过程如下:

class Solution {    public List<Integer> findAnagrams(String s, String p) {        List<Integer> list = new ArrayList();        //判断为空        char[] pchars = p.toCharArray();        int[] freq = new int[256]; //保存p中各个字符的个数        for(char c: pchars){            freq[c]++;        }        int l = 0, r = 0, count = p.length();        while(r < s.length()){            if(freq[s.charAt(r++)]-- >= 1){                //说明当前字符在p中                count--;              }            if(count == 0) list.add(l);            if(r-l == p.length() && freq[s.charAt(l++)]++ >=0 ){                count++;            }        }        return list;    }}

思路很简单:
1. l,r代表滑动窗口的起始点和结束点。用count来代表滑动窗口中,子串包含p字符的个数,初始化为count =p.length()。用freq数组保存p字符串中各个元素出现的次数;
2. 第一个if表示:如果当前字符是p中的字符,那么count–,另外freq[c]对应字符c的次数减一,表示还剩下几个字符c。注意,当字符不是p中字符时,r++;
3. 当count减为0,表示找出了符合条件的子串。那么存入;
4. 接着继续往后找,如果r-l == p.length(),这说明找到了第一个符合条件的子串或者是没找到。接着都需要把l往后滑动一位,这时候需要判断l处的字符是不是p中的字符。若是,还需将l对应字符次数加一,count加一。这样持续循环。

if(count == 0)这个条件必须放在三个if的中间。因为若从l=0,r=0处往后找count个字符正好满足条件的话,这时候需要保存l=0这个值。如若不然(if条件放在第三个),那么在第二个if处又count++,那么count不为0,则结果不完整

原创粉丝点击