title: 每日一練(44):有效的字母異位詞
categories:[劍指offer]
tags:[每日一練]
date: 2022/04/18
每日一練(44):有效的字母異位詞
給定兩個(gè)字符串 s 和 t ,編寫一個(gè)函數(shù)來(lái)判斷 t 是否是 s 的字母異位詞。
注意:若 s 和 t 中每個(gè)字符出現(xiàn)的次數(shù)都相同,則稱 s 和 t 互為字母異位詞。
示例 1:
輸入: s = "anagram", t = "nagaram"
輸出: true
示例 2:
輸入: s = "rat", t = "car"
輸出: false
提示:
1 <= s.length, t.length <= 5 * 104
s 和 t 僅包含小寫字母
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/valid-anagram
方法一:排序
思路分析
t 是 s 的異位詞等價(jià)于「兩個(gè)字符串排序后相等」。因此我們可以對(duì)字符串 s 和 t 分別排序,看排序后的字符串是否相等即可判斷。此外,如果 s 和 t 的長(zhǎng)度
不同,t 必然不是 s 的異位詞。
bool isAnagram(string s, string t) {
if (s.length() != t.length()) {
return false;
}
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
方法二:哈希表
思路分析
由于字符串只包含 26 個(gè)小寫字母,因此我們可以維護(hù)一個(gè)長(zhǎng)度為 26 的頻次數(shù)組 table,先遍歷記錄字符串 s 中字符出現(xiàn)的頻次,然后遍歷字符
串 t,減去 table 中對(duì)應(yīng)的頻次,如果出現(xiàn) table[i]<0,則說明 tt 包含一個(gè)不在 s 中的額外字符,返回 false 即可
bool isAnagram(string s, string t) {
if (s.length() != t.length()) {
return false;
}
vector<int> table(26, 0);
for (auto &ch : s) {
table[ch - 'a']++;
}
for (auto &ch : t) {
table[ch - 'a']--;
if (table[ch - 'a'] < 0) {
return false;
}
}
return true;
}