Skip to content

Commit 02db10e

Browse files
valid anagram
1 parent deaefd8 commit 02db10e

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

EASY/src/easy/ValidAnagram.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package easy;
2+
3+
import java.util.Arrays;
4+
5+
public class ValidAnagram {
6+
public boolean isAnagram_solution1(String s, String t) {
7+
//I even thought about using HashMap to compute their character frequencies respectively and then compare each entry of the two maps, but totally unnecessary.
8+
char[] schar = s.toCharArray();
9+
char[] tchar = t.toCharArray();
10+
Arrays.sort(schar);
11+
Arrays.sort(tchar);
12+
return new String(schar).equals(new String(tchar));
13+
}
14+
15+
//another way: altough much slower
16+
public boolean isAnagram_solution2(String s, String t) {
17+
if(s == null || t == null || s.length() != t.length()) return false;
18+
int[] counts = new int[26];
19+
for(int i = 0; i < s.length(); i++){
20+
counts[s.charAt(i) - 'a']++;
21+
counts[t.charAt(i) - 'a']--;
22+
}
23+
for(int i : counts){
24+
if(i != 0) return false;
25+
}
26+
return true;
27+
}
28+
}

0 commit comments

Comments
 (0)