242.有效的字母异位词
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
字母异位词 是通过重新排列不同单词或短语的字母而形成的单词或短语,通常只使用所有原始字母一次。
示例 1:
输入: s = “anagram”, t = “nagaram”
输出: true
示例 2:
输入: s = “rat”, t = “car”
输出: false
提示:
1 <= s.length, t.length <= 5 * 104
s 和 t 仅包含小写字母
解题思路
代码一
建立hash表,字母和出现频率的映射,分别遍历两个数组,看映射会不会小于零。
class Solution {
public: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;}
};
代码二
对两个字符串排序,如果两个字符串相等,说明符合题意,反之,不符合题意
class Solution {
public:bool isAnagram(string s, string t) {sort(s.begin(),s.end());sort(t.begin(),t.end());if(t==s) return true;else return false;}
};