1、原题如下
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.
2、解题如下
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size()==t.size()&&s.size()==0)
return true;
if(s.size()!=t.size())
return false;
int a[26]={0};
int b[26]={0};
for(int i=0;i<s.size();i++)
{
char m=s[i]-'a';
a[m]++;
}
for(int j=0;j<t.size();j++)
{
char n=t[j]-'a';
b[n]++;
}
for(int k=0;k<26;k++)
{
if(a[k]!=b[k])
return false;
}
return true;
}
};
3、解析
通过读题可以看出本题并不复杂,但是一旦转换成数组来解决就比较麻烦,如上面的解决方案~但是优点是不适用任何algorithm头文件中的函数(其实如上的算法也在一定程度上解决了sort排序的功能)
当然,本题有更好的解法,但需要添加algorithm头文件,如下
if (s.size() != t.size())return false;
sort(s.begin(), s.end()); sort(t.begin(), t.end());
return s == t;
以上参考:https://leetcode.com/discuss/57754/3-lines-c-accepted-solution
以下粘贴sort()函数的用法
MSDN中的定义:
template<class RanIt>
void sort(RanIt first, RanIt last); //--> 1)
template<class RanIt, class Pred>
void sort(RanIt first, RanIt last, Pred pr); //--> 2)
头文件:
#include <algorithm>
using namespace std;
1.默认的sort函数是按升序排。对应于1)
sort(a,a+n); //两个参数分别为待排序数组的首地址和尾地址
2.可以自己写一个cmp函数,按特定意图进行排序。对应于2)
例如:
int cmp(const int &a, const int &b){
if (a > b)
return 1;
else
return 0;
}
sort(a,a+n,cmp);
是对数组a降序排序
又如:
int cmp(const POINT &a, const POINT &b){
if (a.x < b.x)
return 1;
else
if (a.x == b.x){
if (a.y < b.y)
return 1;
else
return 0;
}
else
return 0;
}
sort(a, a + n, cmp);
是先按x升序排序,若x值相等则按y升序排
以上参考:http://blog.youkuaiyun.com/fly_yr/article/details/18894549
4、总结
有空应该加强STL的学习,对你的编程水平的提升会有很大的帮助~