forked from algorithm010/algorithm010
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC_242_valid_anagram.java
More file actions
44 lines (40 loc) · 1.07 KB
/
LC_242_valid_anagram.java
File metadata and controls
44 lines (40 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package Week02;
import java.util.HashMap;
public class LC_242_valid_anagram {
public boolean isAnagram(String s, String t) {
//Brute force
//#1. sort, compare one by one
//#2, HashMap, tracking charaters
//similar with LC_49
if (s.length() != t.length()){
return false;
}
HashMap<Character,Integer> map = new HashMap<>();
for(int i =0; i<s.length();i++){
Character c = s.charAt(i);
if (map.containsKey(c)){
map.replace(c,map.get(c) + 1);
}
else{
map.put(c,1);
}
}
for(int i =0; i<t.length();i++){
Character c = t.charAt(i);
Integer count = map.get(c);
if (count == null){
return false;
}
if (count == 1){
map.remove(c);
}
else {
map.replace(c,--count);
}
}
if (map.isEmpty()){
return true;
}
return false;
}
}