567. Permutation in String
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.
1
2
3
4
5
| Example 1:
Input: s1 = "ab" s2 = "eidbaooo"
Output: True
Explanation: s2 contains one permutation of s1 ("ba").
|
1
2
3
4
| Example 2:
Input:s1= "ab" s2 = "eidboaoo"
Output: False
|
Constraints:
- The input strings only contain lower case letters.
- The length of both given strings is in range [1, 10,000].
Solution#
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
| class Solution {
public boolean checkInclusion(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
int[] count1 = new int[256];
int[] count2 = new int[256];
for (int i = 0; i < len1; i++) {
count1[s1.charAt(i)]++;
}
for (int i = 0; i < len2; i++) {
count2[s2.charAt(i)]++;
if (i >= len1) {
count2[s2.charAt(i - len1)]--;
}
if (Arrays.equals(count1, count2)) {
return true;
}
}
return false;
}
public boolean checkInclusion_RollingHash(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
if (len1 > len2) return false;
int hash1 = 0;
int hash2 = 0;
for (int i = 0; i < len1; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
hash1 += pow(c1);
hash2 += pow(c2);
}
if (hash1 == hash2) {
return true;
}
for (int i = len1; i < len2; i++) {
hash2 = hash2 - pow(s2.charAt(i - len1)) + pow(s2.charAt(i));
if (hash1 == hash2) {
return true;
}
}
return false;
}
int pow(int v) {
return (int) Math.pow(v, 3);
}
}
|