Valid Anagram

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.

利用計數排序將字符串排序


class Solution {
public:
    bool isAnagram(string s, string t) {

        if(strSort(s) == strSort(t))
            return true;
        else
            return false;
    }

private:
    string strSort(string &str)
    {
        int strTime[26] = {0};
        string strToReturn(str.size(), 'a');

        for(int i = 0; i < str.size(); i++)
            strTime[str[i] - 'a']++;

        int postion = 0;
        for(int i = 0; i < 26; i++)
            for(int j = 0; j < strTime[i]; j++)
                strToReturn[postion++] += i;

        return strToReturn;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章