AlgoMaster Logo

Permutation in String

s1=ab,s2=eidbaooo
1public boolean checkInclusion(String s1, String s2) {
2    if (s1.length() > s2.length()) return false;
3
4    int[] s1Count = new int[26];
5    int[] s2Count = new int[26];
6
7    for (int i = 0; i < s1.length(); i++) {
8        s1Count[s1.charAt(i) - 'a']++;
9        s2Count[s2.charAt(i) - 'a']++;
10    }
11
12    for (int i = 0; i < s2.length() - s1.length(); i++) {
13        if (matches(s1Count, s2Count)) return true;
14
15        s2Count[s2.charAt(i + s1.length()) - 'a']++;
16        s2Count[s2.charAt(i) - 'a']--;
17    }
18
19    return matches(s1Count, s2Count);
20}
21
22private boolean matches(int[] s1Count, int[] s2Count) {
23    for (int i = 0; i < 26; i++) {
24        if (s1Count[i] != s2Count[i]) return false;
25    }
26    return true;
27}
0 / 13
s1:abs2:eidbaooos1Count = {}s2Count = {}