|
31 | 31 | The substring with start index = 2 is "ab", which is an anagram of "ab".*/
|
32 | 32 |
|
33 | 33 | 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 | + } |
42 | 44 | }
|
| 45 | + return result; |
43 | 46 | }
|
44 |
| - return result; |
45 |
| - } |
46 | 47 |
|
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 | + } |
53 | 54 |
|
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 | + } |
57 | 59 | }
|
| 60 | + return true; |
58 | 61 | }
|
59 |
| - return true; |
60 | 62 | }
|
61 | 63 |
|
62 | 64 |
|
63 |
| - static class SlidingWindowSolution { |
| 65 | + public static class Solution2 { |
| 66 | + /** |
| 67 | + * Slinding Window |
| 68 | + */ |
64 | 69 | public List<Integer> findAnagrams(String s, String p) {
|
65 | 70 | List<Integer> result = new ArrayList();
|
66 | 71 | int[] hash = new int[26];
|
@@ -94,7 +99,7 @@ public List<Integer> findAnagrams(String s, String p) {
|
94 | 99 | }
|
95 | 100 |
|
96 | 101 | public static void main(String... args) {
|
97 |
| - SlidingWindowSolution test = new SlidingWindowSolution(); |
| 102 | + Solution2 test = new Solution2(); |
98 | 103 | String s = "cbaebabacd";
|
99 | 104 | String p = "abc";
|
100 | 105 | test.findAnagrams(s, p);
|
|
0 commit comments