天天看點

leetcode 242 :Valid Anagram

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()==)
            return true;
        if(s.size()!=t.size())
            return false;
        int a[]={};
        int b[]={};
        for(int i=;i<s.size();i++)
        {
            char m=s[i]-'a';
            a[m]++;
        }
        for(int j=;j<t.size();j++)
        {
            char n=t[j]-'a';
            b[n]++;
        }
        for(int k=;k<;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;

預設的sort函數是按升序排。對應于)
sort(a,a+n); //兩個參數分别為待排序數組的首位址和尾位址
可以自己寫一個cmp函數,按特定意圖進行排序。對應于)
例如:
int cmp(const int &a, const int &b){
    if (a > b)
        return ;
    else
        return ;
}
sort(a,a+n,cmp);
是對數組a降序排序
又如:
int cmp(const POINT &a, const POINT &b){
    if (a.x < b.x)
        return ;
    else
    if (a.x == b.x){
        if (a.y < b.y)
            return ;
        else
            return ;
    }
    else
        return ;
}
sort(a, a + n, cmp);
是先按x升序排序,若x值相等則按y升序排
           

以上參考:http://blog.csdn.net/fly_yr/article/details/18894549

4、總結

有空應該加強STL的學習,對你的程式設計水準的提升會有很大的幫助~