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 * 104
s
andt
consist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
n = len(s)
chars = [0] * 26
for i in range(n):
chars[ord(s[i]) - ord('a')] += 1
chars[ord(t[i]) - ord('a')] -= 1
for i in range(26):
if chars[i] != 0:
return False
return True
class Solution {
public boolean isAnagram(String s, String t) {
int n;
if ((n = s.length()) != t.length()) {
return false;
}
int[] chars = new int[26];
for (int i = 0; i < n; ++i) {
++chars[s.charAt(i) - 'a'];
--chars[t.charAt(i) - 'a'];
}
for (int i = 0; i < 26; ++i) {
if (chars[i] != 0) {
return false;
}
}
return true;
}
}