-
Notifications
You must be signed in to change notification settings - Fork 0
/
validAnagram.java
46 lines (42 loc) · 1.08 KB
/
validAnagram.java
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
45
46
// Given two strings s and t , write a function to determine if t is an anagram of s.
// Example 1:
// Input: s = "anagram", t = "nagaram"
// Output: true
// Example 2:
// Input: s = "rat", t = "car"
// Output: false
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()){
return false;
}
HashMap <Character, Integer> map = new HashMap<>();
for(int i=0; i<s.length(); i++){
if(map.containsKey(s.charAt(i))){
int count = map.get(s.charAt(i));
count++;
map.put(s.charAt(i),count);
} else {
int count=1;
map.put(s.charAt(i),count);
}
}
for(int i =0; i<t.length(); i++){
if(map.containsKey(t.charAt(i))){
int count = map.get(t.charAt(i));
count--;
map.put(t.charAt(i), count);
} else {
return false;
}
}
Iterator it = map.values().iterator();
while(it.hasNext()){
int count = (int) it.next();
if(count!=0){
return false;
}
}
return true;
}
}