问题描述:
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的一种排列方式。
这种问题可以有两种基本解法:
1.利用排序,比较排序后的s和t是否相同
2.利用hash table 统计每个字符串线的次数,然后对比两者是否数量相同即可。
这里我们只给出第一种方式的代码:
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.length() != t.length()) return false;
if(s == "" && t == "") return true;
sort(s.begin(),s.end());
sort(t.begin(),t.end());
for(int i = 0; i < s.length(); i++)
{
if(s[i] != t[i]) return false;
}
return true;
}
};