ID | Title | Difficulty | |
---|---|---|---|
Loading... |
242. Valid Anagram
Easy
LeetCode
Hash Table, String, Sorting
Problem
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
Note: You may assume the string contains only lowercase alphabets.
Follow up: What if the inputs contain unicode characters? How would you adapt your solution to such case?
Code
class Solution {
public boolean isAnagram(String s, String t) {
if(s == null && t == null) return true;
if(s == null || t == null) return false;
if(s.length() != t.length()) return false;
int[] dict = new int[26];
for(int i = 0; i < s.length(); i++) {
dict[s.charAt(i) - 'a']++;
dict[t.charAt(i) - 'a']--;
}
for(int num : dict) {
if(num != 0) return false;
}
return true;
}
}
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
map = defaultdict(int)
for i in range(len(s)):
map[s[i]] += 1
map[t[i]] -= 1
for v in map.values():
if v != 0:
return False
return True
按 <- 键看上一题!
241. Different Ways to Add Parentheses
按 -> 键看下一题!
243. Shortest Word Distance