|
| 1 | +package easy; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +public class FindAllAnagramsinaString { |
| 7 | + /**O(m*n) solution, my original and most intuitive one, but kind of brute force.*/ |
| 8 | + public List<Integer> findAnagrams(String s, String p) { |
| 9 | + List<Integer> result = new ArrayList(); |
| 10 | + for (int i = 0; i <= s.length()-p.length(); i++){ |
| 11 | + if (isAnagram(s.substring(i, i+p.length()), p)) result.add(i); |
| 12 | + } |
| 13 | + return result; |
| 14 | + } |
| 15 | + |
| 16 | + private boolean isAnagram(String s, String p){ |
| 17 | + int[] c = new int[26]; |
| 18 | + for (int i = 0; i < s.length(); i++){ |
| 19 | + c[s.charAt(i) - 'a']++; |
| 20 | + c[p.charAt(i) - 'a']--; |
| 21 | + } |
| 22 | + |
| 23 | + for (int i : c){ |
| 24 | + if(i != 0) return false; |
| 25 | + } |
| 26 | + return true; |
| 27 | + } |
| 28 | + |
| 29 | + |
| 30 | + static class SlidingWindowSolution { |
| 31 | + /**O(n) solution inspired by this post: https://discuss.leetcode.com/topic/64434/shortest-concise-java-o-n-sliding-window-solution*/ |
| 32 | + public List<Integer> findAnagrams(String s, String p) { |
| 33 | + List<Integer> result = new ArrayList(); |
| 34 | + int[] hash = new int[26]; |
| 35 | + for (char c : p.toCharArray()){ |
| 36 | + hash[c - 'a']++; |
| 37 | + } |
| 38 | + int start = 0, end = 0, count = p.length(); |
| 39 | + while (end < s.length()){ |
| 40 | + if(hash[s.charAt(end) - 'a'] > 0){ |
| 41 | + count--; |
| 42 | + } |
| 43 | + hash[s.charAt(end) - 'a']--; |
| 44 | + end++; |
| 45 | + |
| 46 | + if(count == 0) result.add(start); |
| 47 | + |
| 48 | + if((end - start) == p.length()){ |
| 49 | + if(hash[s.charAt(start) - 'a'] >= 0) count++; |
| 50 | + hash[s.charAt(start) - 'a']++; |
| 51 | + start++; |
| 52 | + } |
| 53 | + } |
| 54 | + return result; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + public static void main(String...args){ |
| 59 | + SlidingWindowSolution test = new SlidingWindowSolution(); |
| 60 | + String s = "cbaebabacd"; |
| 61 | + String p = "abc"; |
| 62 | + test.findAnagrams(s, p); |
| 63 | + } |
| 64 | +} |
0 commit comments