|
| 1 | +packageeasy; |
| 2 | + |
| 3 | +importjava.util.ArrayList; |
| 4 | +importjava.util.List; |
| 5 | + |
| 6 | +publicclassFindAllAnagramsinaString { |
| 7 | +/**O(m*n) solution, my original and most intuitive one, but kind of brute force.*/ |
| 8 | +publicList<Integer>findAnagrams(Strings,Stringp) { |
| 9 | +List<Integer>result =newArrayList(); |
| 10 | +for (inti =0;i <=s.length()-p.length();i++){ |
| 11 | +if (isAnagram(s.substring(i,i+p.length()),p))result.add(i); |
| 12 | + } |
| 13 | +returnresult; |
| 14 | + } |
| 15 | + |
| 16 | +privatebooleanisAnagram(Strings,Stringp){ |
| 17 | +int[]c =newint[26]; |
| 18 | +for (inti =0;i <s.length();i++){ |
| 19 | +c[s.charAt(i) -'a']++; |
| 20 | +c[p.charAt(i) -'a']--; |
| 21 | + } |
| 22 | + |
| 23 | +for (inti :c){ |
| 24 | +if(i !=0)returnfalse; |
| 25 | + } |
| 26 | +returntrue; |
| 27 | + } |
| 28 | + |
| 29 | + |
| 30 | +staticclassSlidingWindowSolution { |
| 31 | +/**O(n) solution inspired by this post: https://discuss.leetcode.com/topic/64434/shortest-concise-java-o-n-sliding-window-solution*/ |
| 32 | +publicList<Integer>findAnagrams(Strings,Stringp) { |
| 33 | +List<Integer>result =newArrayList(); |
| 34 | +int[]hash =newint[26]; |
| 35 | +for (charc :p.toCharArray()){ |
| 36 | +hash[c -'a']++; |
| 37 | + } |
| 38 | +intstart =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 | +returnresult; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | +publicstaticvoidmain(String...args){ |
| 59 | +SlidingWindowSolutiontest =newSlidingWindowSolution(); |
| 60 | +Strings ="cbaebabacd"; |
| 61 | +Stringp ="abc"; |
| 62 | +test.findAnagrams(s,p); |
| 63 | + } |
| 64 | +} |