一、題目描述
給定兩個字符串 s 和 t ,編寫一個函數來判斷 t 是否是 s 的字母異位詞。
示例 1:
輸入: s = "anagram", t = "nagaram"
輸出: true
示例 2:
輸入: s = "rat", t = "car"
輸出: false
說明:
你可以假設字符串只包含小寫字母。
進階:
如果輸入字符串包含 unicode 字符怎麼辦?你能否調整你的解法來應對這種情況?
二、題解思路
- 暴力的,排序後直接比較;
- 一個數組,第一個字符串有就+1,第二字符串有就-1,之後數組的每個元素是0則返回true;
三、程序示例
class Solution {
public:
bool isAnagram1(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t ? true : false;
}
bool isAnagram(string s, string t) {
int count[26] = {0};
for(auto ch : s)
count[ ch - 'a' ] += 1;
for(auto ch : t)
count[ ch - 'a' ] -= 1;
for(int i = 0; i < 26; i++)
{
if(count[i] != 0)
return false;
}
return true;
}
};