Skip to content

Commit 5d4f6f8

Browse files
[N-0] refactor 438
1 parent 5c6306c commit 5d4f6f8

File tree

1 file changed

+27
-22
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+27
-22
lines changed

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

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -31,36 +31,41 @@
3131
The substring with start index = 2 is "ab", which is an anagram of "ab".*/
3232

3333
public class _438 {
34-
/**
35-
* O(m*n) solution, my original and most intuitive one, but kind of brute force.
36-
*/
37-
public List<Integer> findAnagrams(String s, String p) {
38-
List<Integer> result = new ArrayList();
39-
for (int i = 0; i <= s.length() - p.length(); i++) {
40-
if (isAnagram(s.substring(i, i + p.length()), p)) {
41-
result.add(i);
34+
public static class Solution1 {
35+
/**
36+
* O(m*n) solution, my original and most intuitive one, but kind of brute force.
37+
*/
38+
public List<Integer> findAnagrams(String s, String p) {
39+
List<Integer> result = new ArrayList();
40+
for (int i = 0; i <= s.length() - p.length(); i++) {
41+
if (isAnagram(s.substring(i, i + p.length()), p)) {
42+
result.add(i);
43+
}
4244
}
45+
return result;
4346
}
44-
return result;
45-
}
4647

47-
private boolean isAnagram(String s, String p) {
48-
int[] c = new int[26];
49-
for (int i = 0; i < s.length(); i++) {
50-
c[s.charAt(i) - 'a']++;
51-
c[p.charAt(i) - 'a']--;
52-
}
48+
private boolean isAnagram(String s, String p) {
49+
int[] c = new int[26];
50+
for (int i = 0; i < s.length(); i++) {
51+
c[s.charAt(i) - 'a']++;
52+
c[p.charAt(i) - 'a']--;
53+
}
5354

54-
for (int i : c) {
55-
if (i != 0) {
56-
return false;
55+
for (int i : c) {
56+
if (i != 0) {
57+
return false;
58+
}
5759
}
60+
return true;
5861
}
59-
return true;
6062
}
6163

6264

63-
static class SlidingWindowSolution {
65+
public static class Solution2 {
66+
/**
67+
* Slinding Window
68+
*/
6469
public List<Integer> findAnagrams(String s, String p) {
6570
List<Integer> result = new ArrayList();
6671
int[] hash = new int[26];
@@ -94,7 +99,7 @@ public List<Integer> findAnagrams(String s, String p) {
9499
}
95100

96101
public static void main(String... args) {
97-
SlidingWindowSolution test = new SlidingWindowSolution();
102+
Solution2 test = new Solution2();
98103
String s = "cbaebabacd";
99104
String p = "abc";
100105
test.findAnagrams(s, p);

0 commit comments

Comments
 (0)