0567. Permutation in String

https://leetcode.com/problems/permutation-in-string

Description

Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

In other words, return true if one of s1's permutations is the substring of s2.

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

Constraints:

  • 1 <= s1.length, s2.length <= 104

  • s1 and s2 consist of lowercase English letters.

ac

class Solution {
    public boolean checkInclusion(String s1, String s2) {
        // edge cases
        if (s2.length() == 0) return false;
        if (s1.length() == 0) return true;

        // get char counts
        int len1 = s1.length(), len2 = s2.length();
        int diff = 0; // how many different chars
        int[] map = new int[26];
        for (char c : s1.toCharArray()) {
            map[c-'a']++;
            if (map[c-'a'] == 1) diff++;
        }

        // initial window
        int l = 0;
        for (int r = 0; r < len2; r++) {
            char c = s2.charAt(r);
            map[c-'a']--;
            if (map[c-'a'] == 0) diff--;
            else if (map[c-'a'] == -1) diff++;

            if (r - l >= len1) { // window length is s1's length
                char lc = s2.charAt(l++);  // move left point forward
                map[lc-'a']++;
                if (map[lc-'a'] == 0) diff--;
                else if (map[lc-'a'] == 1) diff++;
            }

            if (diff == 0) return true;
        }

        return false;
    }
}

Last updated