0242 - Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Examples
Input: s = "anagram", t = "nagaram" Output: true
Input: s = "rat", t = "car" Output: false
Constraints
1 <= s.length, t.length <= 5 * 104 s and t consist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
Java Solution
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length() != t.length()) return false;
HashMap<Character, Integer> hm = new HashMap<>();
for(int i = 0; i < s.length(); i++) {
hm.put(s.charAt(i), hm.getOrDefault(s.charAt(i), 0) + 1);
}
for(int i = 0; i < t.length(); i++){
if(!hm.containsKey(t.charAt(i))) return false;
hm.put(t.charAt(i), hm.get(t.charAt(i))-1);
if(hm.get(t.charAt(i)) < 0) return false;
}
return true;
}
}
Last updated