題目
給定兩個(gè)字符串 s 和 t ,編寫一個(gè)函數(shù)來判斷 t 是否是 s 的字母異位詞。
示例 1:
輸入: s = "anagram", t = "nagaram"
輸出: true
示例 2:
輸入: s = "rat", t = "car"
輸出: false
說明:
你可以假設(shè)字符串只包含小寫字母。
進(jìn)階:
如果輸入字符串包含 unicode 字符怎么辦?你能否調(diào)整你的解法來應(yīng)對(duì)這種情況?
思路
哈希表
先遍歷一遍字符串s,將s中每個(gè)字符及其對(duì)應(yīng)的次數(shù)存入哈希表中,然后遍歷一遍字符串t,判斷是否存在字符串s中,不存在返回false,遍歷結(jié)束后判斷哈希表中是否有剩余,有返回False
時(shí)間復(fù)雜度:O(n) 遍歷字符串的時(shí)間
空間復(fù)雜度:O(n)
python
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
sets = {}
for c in s:
if c in sets:
sets[c] += 1
else:
sets[c] = 1
for c in t:
if c in sets:
sets[c] -= 1
if sets[c] == 0:
sets.pop(c)
else:
return False
if len(sets) != 0:
return False
return True
c++
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size()) return false;
unordered_map<char, int> map;
for(char c : s) map[c] ++;
for(char c : t)
if(-- map[c] == -1) return false;
return true;
}
};