[LeetCode] Permutation in String

567. Permutation in String

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
bool checkInclusion(string s1, string s2) {
if(s1.length() > s2.length()) return false;
int n = s1.length();
vector<int> v1(26,0);
for(auto& ch : s1) v1[ch-'a']++;
for(int i = 0; i < n; i++) v1[s2[i]-'a']--;
bool check = true;
for(int i = 0; i < 26; i++)
if(v1[i]) {check = false; break;}
if(check) return true;
for(int i = n; i < s2.length(); i++) {
v1[s2[i]-'a']--;
v1[s2[i-n]-'a']++;
check = true;
for(int i = 0; i < 26; i++)
if(v1[i]) {check = false; break;}
if(check) return true;
}

return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/11/PS/LeetCode/permutation-in-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.