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经过调整位置得到,则这两个字符出现的次数是相等的。
源代码:
1 class Solution { 2 public: 3 bool isAnagram(string s, string t) { 4 if(s.size()!=t.size()) return false; 5 map<char,int> cnt; 6 for(int i = 0 ; i < s.size(); ++ i) cnt[s[i]]++; 7 for(int i = 0; i < t.size(); ++ i) cnt[t[i]]--; 8 for(map<char,int>::iterator iter = cnt.begin(); iter!=cnt.end(); ++ iter){ 9 if(iter->second!=0)return false; 10 } 11 return true; 12 } 13 };