Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 419e173

Browse files
edit 242
1 parent ccf5173 commit 419e173

File tree

1 file changed

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

1 file changed

+27
-20
lines changed

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

Lines changed: 27 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
import java.util.Arrays;
44

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.
68
79
For example,
810
s = "anagram", t = "nagaram", return true.
@@ -12,28 +14,33 @@
1214
You may assume the string contains only lowercase alphabets.
1315
1416
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+
*/
1619

1720
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));
3329
}
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;
3644
}
37-
return true;
3845
}
3946
}

0 commit comments

Comments
 (0)