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.
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 * 10^4
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?
【C++】
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) {
return false;
}
vector<int> counts(26, 0);
for (int i = 0; i < s.length(); ++i) {
++counts[s[i]-'a'];
--counts[t[i]-'a'];
}
for (int i = 0; i < 26; ++i) {
if (counts[i]) {
return false;
}
}
return true;
}
};
或者
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) {return false;}
int cnts[26] = {0};
for(char c : s) {cnts[c-'a']++;}
for(char c : t) {cnts[c-'a']--;}
for(int cnt : cnts) if (cnt != 0) {return false;}
return true;
}
};
【Java】
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {return false;}
int[] cnts = new int[26];
Arrays.fill(cnts, 0);
for (int i = 0; i < s.length(); ++i) {
++cnts[s.charAt(i)-'a'];
--cnts[t.charAt(i)-'a'];
}
for (int cnt : cnts) if (cnt != 0) {return false;}
return true;
}
}