题目:

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.

 

思路:

1.第一反应:直接sort两个串,然后比较这两个串    Θ(nlogn)

2.利用计数排序的思路,用一个数组a[26]记录每个字母的个数在s中出现则++,在t中出现则--,最后判断是否全为0(assume the string contains only lowercase alphabets) Θ(n)

 

代码 C++ 思路1:

class Solution {
public:
    bool isAnagram(string s, string t) {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        if (s == t)
            return true;
        else
            return false;
    }
};

C++ 思路2:

class Solution {
public:
    bool isAnagram(string s, string t) {
        int a[26];
        for (int i = 0; i < 26; i++) {
            a[i] = 0;
        }
        for (int i = 0; i < s.size(); i++) {
            a[s[i] - 'a']++;
        }
        for (int i = 0; i < t.size(); i++) {
            a[t[i] - 'a']--;
        }
        for (int i = 0; i < 26; i++) {
            if (a[i] != 0)
                return false;
        }
        return true;
    }
};

 

posted on 2016-02-03 12:54  gavinXing  阅读(163)  评论(0编辑  收藏  举报