567. Permutation in String

yPhantom 2019年10月24日 34次浏览

原题链接

Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.

Example 1:

Input: s1 = "ab" s2 = "eidbaooo"
Output: True
Explanation: s2 contains one permutation of s1 ("ba").

Example 2:

Input:s1= "ab" s2 = "eidboaoo"
Output: False

Note:

  1. The input strings only contain lower case letters.
  2. The length of both given strings is in range [1, 10,000].

Solution

窗口法。根据窗口中各个字符的频次,全是0代表是一个排序。

Java版

class Solution {

    public boolean checkInclusion(String s1, String s2) {
        int n = s1.length();
        if (n > s2.length()) {
            return false;
        }
        int[] count = new int[26];
        for (int i = 0; i < n; i++) {
            count[s1.charAt(i) - 'a']++;
            count[s2.charAt(i) - 'a']--;
        }
        if (allZero(count)) {
            return true;
        }
        for (int i = n; i < s2.length(); i++) {
            count[s2.charAt(i) - 'a']--;
            count[s2.charAt(i - n) - 'a']++;
            if (allZero(count)) {
                return true;
            }
        }
        return false;
    }
    
    private boolean allZero(int[] count) {
        for (int num: count) {
            if (num != 0) {
                return false;
            }
        }
        return true;
    }
}