[LeetCode] Sliding Window 系列

438 Find All Anagrams in a String

题目:
给String s和非空String p,找到所有p的回文在s中的起始点。
给的String只含有小写字母。s和p的长度不超过20,100。答案的顺序无关。

例子:
Input: s: "cbaebabacd" p: "abc"
Output: [0, 6]

Input: s: "abab" p: "ab"
Output: [0, 1, 2]

代码:

public class Solution {
    public List findAnagrams(String s, String p) {
        List res = new ArrayList<>();
        if (s.length() == 0) {
            return res;
        }
        
        int[] chars = new int[256];
        
        for (int i = 0; i < p.length(); i++) {
            chars[p.charAt(i)]++; // p中每个字符的个数,也就是待match的个数
        }
        
        // two points: left是s要匹配的左边界
        int left = 0, right = 0, count = p.length(); // count: 要匹配的个数
        while (right < s.length()) {
            if (chars[s.charAt(right)] >= 1) { // current hash value >= 1: p中存在这个char
                count--; // move right everytime, 如果s中这个字符在p里出现了, decrease the count
            }
            chars[s.charAt(right)]--; // 待match个数减1,负数说明不该有这个char,但是出现了
            right++; // 右边界右移,继续匹配
            
            if (count == 0) { // 全部匹配
                res.add(left);
            }
        
            // if we find the window's size equals to p, then move left (narrow the window) to find the new match window
            // ++ to reset the hash because we kicked out the left
            // only increase the count if the character is in p
            // the count >= 0 indicate it was original in the hash, cuz it won't go below 0
            if (right - left == p.length()) { // 已经check了p.len个,不管是不是匹配
                if (chars[s.charAt(left)] >= 0) { // 曾经作为匹配字符出现过,也就是在p里出现过
                    count++; // left被剔除,所以还需要left的字符进行匹配 
                }
                chars[s.charAt(left)]++; // left被剔除,所以hash里面个数加回来
                left++;
            }
        }
        return res;
    }
}

其他相关题目

567 Permutation in String
https://leetcode.com/problems/permutation-in-string/

你可能感兴趣的:([LeetCode] Sliding Window 系列)