Skip to content

Commit 4604148

Browse files
add a solution for 567
1 parent bcde39a commit 4604148

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

src/main/java/com/fishercoder/solutions/_567.java

+42
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,46 @@ private boolean allZeroes(int[] count) {
4343
return true;
4444
}
4545
}
46+
47+
public static class Solution2 {
48+
/**
49+
* A classic sliding window problem.
50+
* I came up with below solution independently on 9/17/2021.
51+
* <p>
52+
* A few pointers that led me to the sliding window approach:
53+
* 1. if it's a valid permutation, the substring from S2 must have equal length as of s1;
54+
* 2. I don't want to repeatedly calculate each and every possible substring of s2, if s1 is really long, this could mean lots of redundant calculation.
55+
* So sliding window to the rescue!
56+
*/
57+
public boolean checkInclusion(String s1, String s2) {
58+
if (s1.length() > s2.length()) {
59+
return false;
60+
}
61+
int[] count = new int[26];
62+
for (char c : s1.toCharArray()) {
63+
count[c - 'a']++;
64+
}
65+
for (int i = 0; i < s1.length(); i++) {
66+
count[s2.charAt(i) - 'a']--;
67+
}
68+
for (int i = s1.length(), j = 0; i < s2.length(); i++, j++) {
69+
if (isPermutation(count)) {
70+
return true;
71+
} else {
72+
count[s2.charAt(j) - 'a']++;
73+
count[s2.charAt(i) - 'a']--;
74+
}
75+
}
76+
return isPermutation(count);
77+
}
78+
79+
private boolean isPermutation(int[] count) {
80+
for (int c : count) {
81+
if (c != 0) {
82+
return false;
83+
}
84+
}
85+
return true;
86+
}
87+
}
4688
}

src/test/java/com/fishercoder/_567Test.java

+13
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
public class _567Test {
1010
private static _567.Solution1 solution1;
11+
private static _567.Solution2 solution2;
1112
private static boolean expected;
1213
private static boolean actual;
1314
private static String s1;
@@ -16,6 +17,7 @@ public class _567Test {
1617
@BeforeClass
1718
public static void setup() {
1819
solution1 = new _567.Solution1();
20+
solution2 = new _567.Solution2();
1921
}
2022

2123
@Test
@@ -24,6 +26,17 @@ public void test1() {
2426
s2 = "eidbaooo";
2527
expected = true;
2628
actual = solution1.checkInclusion(s1, s2);
29+
actual = solution2.checkInclusion(s1, s2);
30+
assertEquals(expected, actual);
31+
}
32+
33+
@Test
34+
public void test2() {
35+
s1 = "adc";
36+
s2 = "dcda";
37+
expected = true;
38+
actual = solution1.checkInclusion(s1, s2);
39+
actual = solution2.checkInclusion(s1, s2);
2740
assertEquals(expected, actual);
2841
}
2942
}

0 commit comments

Comments
 (0)