LeetCode(242)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.

分析

判断给定两个字符串是否为相同字母不同排列的单词。

最简单的办法就是调用stl的排序函数sort给两个字符串s和t排序,然后比较是否相等即可,复杂度为O(nlogn);

如果嫌弃复杂度太高,还可以采用另外一种办法求每个字符个数判相等(题目已经假设只有小写字母那么也就只有26个),比较是否相等,复杂度为O(n);

AC代码

class Solution {
public:
    //方法一:排序判断
    bool isAnagram1(string s, string t) {
        if (s.empty() && t.empty())
            return true;
        else if (s.empty() || t.empty())
            return false;

        sort(s.begin(), s.end());
        sort(t.begin(), t.end());

        if (s == t)
            return true;
        return false;       
    }
    //方法二:字母个数判相等
    bool isAnagram(string s, string t) {
        vector<int> count(26, 0);
        for (int i = 0; i < s.size(); i++)
            count[s[i] - 'a'] ++;
        for (int i = 0; i < t.size(); i++)
            count[t[i] - 'a'] --;
        for (int i = 0; i < 26; i++)
        if (count[i] != 0)
            return false;
        return true;
    }
};

GitHub测试程序源码

原文地址:https://www.cnblogs.com/shine-yr/p/5214758.html