567. Permutation in String

567. Permutation in String

Description

Difficulty: Medium

Related Topics: Hash Table, Two Pointers, String, Sliding Window

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:

1
2
3
Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").

Example 2:

1
2
Input: s1 = "ab", s2 = "eidboaoo"
Output: false

Constraints:

  • 1 <= s1.length, s2.length <= 104
  • s1 and s2 consist of lowercase English letters.

Hints/Notes

  • Sliding window

Details

  • 2023/08/10
  • Compile a map to record needing characters first
  • Sliding window, use a map to record in window characters, use a variable(valid) to record the number of characters satisfy the occurrence requirement
  • No solution from 0x3F

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        unordered_map<charint> need, window;
        for (char c : s1) {
            need[c]++;
        }
        int left = 0, right = 0, valid = 0, len = s1.size();
        while (right < s2.size()) {
            char c = s2[right++];
            if (need.count(c)) {
                window[c]++;
                if (window[c] == need[c]) {
                    valid++;
                }
            }
            if (right - left == len) {
                if (valid == need.size()) {
                    return true;
                }
                c = s2[left++];
                if (need.count(c)) {
                    if (window[c] == need[c]) {
                        valid--;
                    }
                    window[c]--;
                }
            }
        }
        return false;
    }
};