Given two strings s and t, write a function to determine if t is an anagram of s.
For example,s = "anagram", t = "nagaram", return true.s = "rat", t = "car", return false.
Note:You may assume the string contains only lowercase alphabets.
思路:
给定两个字符串s和t,写一个函数,判断t是否是s的变位词。
如果t跟s包含相同字符但排列顺序不同,则称t是s的变位词。
那么分别计算两个字符串中每个字母出现次数,然后再比较即可。第二种思路是把字符串看作字符数组,将两个字符数组分别排序,所得结果若相同,则说明两个字符串互为变位词。
代码1:
class Solution { public: bool isAnagram(string s, string t) { map<char,int> ss,tt; for(char ch:s){ss[ch]++;} for(char ch:t){tt[ch]++;} map<char,int>::iterator poss=ss.begin(),post=tt.begin(); for(;poss!=ss.end() && post!=tt.end();poss++,post++){ if(poss->first!=post->first || poss->second!=post->second){return false;} } if(poss!=ss.end() || post!=tt.end()){return false;} else{return true;} } };代码2:
class Solution { public: bool isAnagram(string s, string t) { map<char,int> m; for(char ch:s){m[ch]++;} for(char ch:t){m[ch]--;} for(pair<char,int> mm:m){ if(mm.second!=0){return false;} } return true; } };代码3:
class Solution { public: bool isAnagram(string s, string t) { int arr[26] = {}; for (int i = 0; i < s.size(); i++) {arr[s[i] - 'a']++;} for (int i = 0; i < t.size(); i++) {arr[t[i] - 'a']--;} for (int i = 0; i < 26; i++) { if (arr[i] != 0) {return false;} } return true; } };