This question is part of NeetCode150 series.
Problem Description
Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Solution
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
class Solution {
public boolean isAnagram(String s, String t) {
Map<Character, Integer> map = new HashMap<>();
for(int i=0; i<s.length(); i++){
Character c = s.charAt(i);
if(map.containsKey(c)){
int frequency = map.get(c);
map.put(c, frequency+1);
}else{
map.put(c, 1);
}
}
for(int i=0; i<t.length(); i++){
Character x = t.charAt(i);
if(!map.containsKey(x)){
return false;
}else{
int frequency = map.get(x);
if(frequency == 1){
map.remove(x);
}else{
map.put(x, frequency-1);
}
}
}
return map.size()==0?true:false;
}
}