|
2 | 2 |
|
3 | 3 | import java.util.Arrays;
|
4 | 4 |
|
5 |
| -/**Given two strings s and t, write a function to determine if t is an anagram of s. |
| 5 | +/** |
| 6 | + * 242. Valid Anagram |
| 7 | + * Given two strings s and t, write a function to determine if t is an anagram of s. |
6 | 8 |
|
7 | 9 | For example,
|
8 | 10 | s = "anagram", t = "nagaram", return true.
|
|
12 | 14 | You may assume the string contains only lowercase alphabets.
|
13 | 15 |
|
14 | 16 | Follow up:
|
15 |
| - What if the inputs contain unicode characters? How would you adapt your solution to such case?*/ |
| 17 | + What if the inputs contain unicode characters? How would you adapt your solution to such case? |
| 18 | + */ |
16 | 19 |
|
17 | 20 | public class _242 {
|
18 |
| - public boolean isAnagram_solution1(String s, String t) { |
19 |
| - char[] schar = s.toCharArray(); |
20 |
| - char[] tchar = t.toCharArray(); |
21 |
| - Arrays.sort(schar); |
22 |
| - Arrays.sort(tchar); |
23 |
| - return new String(schar).equals(new String(tchar)); |
24 |
| - } |
25 |
| - |
26 |
| - //another way: although much slower |
27 |
| - public boolean isAnagram_solution2(String s, String t) { |
28 |
| - if(s == null || t == null || s.length() != t.length()) return false; |
29 |
| - int[] counts = new int[26]; |
30 |
| - for(int i = 0; i < s.length(); i++){ |
31 |
| - counts[s.charAt(i) - 'a']++; |
32 |
| - counts[t.charAt(i) - 'a']--; |
| 21 | + |
| 22 | + public static class SortingSolution { |
| 23 | + public boolean isAnagram(String s, String t) { |
| 24 | + char[] schar = s.toCharArray(); |
| 25 | + char[] tchar = t.toCharArray(); |
| 26 | + Arrays.sort(schar); |
| 27 | + Arrays.sort(tchar); |
| 28 | + return new String(schar).equals(new String(tchar)); |
33 | 29 | }
|
34 |
| - for(int i : counts){ |
35 |
| - if(i != 0) return false; |
| 30 | + } |
| 31 | + |
| 32 | + public static class CountingSolution { |
| 33 | + public boolean isAnagram(String s, String t) { |
| 34 | + if (s == null || t == null || s.length() != t.length()) return false; |
| 35 | + int[] counts = new int[26]; |
| 36 | + for (int i = 0; i < s.length(); i++) { |
| 37 | + counts[s.charAt(i) - 'a']++; |
| 38 | + counts[t.charAt(i) - 'a']--; |
| 39 | + } |
| 40 | + for (int i : counts) { |
| 41 | + if (i != 0) return false; |
| 42 | + } |
| 43 | + return true; |
36 | 44 | }
|
37 |
| - return true; |
38 | 45 | }
|
39 | 46 | }
|
0 commit comments