Valid Anagram ---leetcode

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.

思路:首先判断数字符个数是否相等;然后再进行比较。

c++:

class solution
{
public :
    bool isanagram(string s,string t)
    {
        if(s.length()!=t.length()) return false;
        int com[26]= {0};
        for (int i=0; i<s.length(); i++)
        {
            com[s[i]-'a']++;//统计s[i]所对应的的字母出现的次数
            com[t[i]-'a']--;//统计t[i]所对应的的字母出现的次数
        }

        for (int i=0; i<26; i++)
        {
            if (com[i]!=0) return false;
        }
        return true;
    }
};

当然还有更简单的,就是时间复杂度较高:

class solution
{
public :
    bool isanagram(string s,string t)
    {
        if(s.length()!=t.length()) return false;
        sort(s.begin(),s.end());
        sort(t.begin(),s.end());
        if(s==t) return true;
        else return false;
    }
}

你可能感兴趣的:(LeetCode)