242. Valid Anagram
2026/1/12小于 1 分钟约 274 字
242. Valid Anagram
难度: Easy
题目描述
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Constraints:
1 <= s.length, t.length <= 5 * 104sandtconsist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
解题思路
代码实现
解决方案
java
class Solution {
public boolean isAnagram(String s, String t) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
}
for (int i = 0; i < t.length(); i++) {
if (map.get(t.charAt(i)) == null) {
return false;
}
map.put(t.charAt(i), map.get(t.charAt(i)) - 1);
if (map.get(t.charAt(i)) == 0) {
map.remove(t.charAt(i));
}
}
return map.size() == 0;
}
}