异位词

leecode上一道简单题目:给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true

示例 2:

输入: s = "rat", t = "car"
输出: false

说明:
你可以假设字符串只包含小写字母。

class Solution {
public:
    bool isAnagram(string s, string t) {
        int len1 = s.size();
        int len2 = t.size();
        if(len1 != len2) {
            return false;
        } 
        sort(s.begin(), s.end(), [](const char&a, const char&b) {return a > b;} );
        sort(t.begin(), t.end(), [](const char&a, const char&b) {return a > b;} );
        for(int i = 0; i < s.size(); i++)
        {
            if(s[i] != t[i]) 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(), t.end());
        return s == t;
    }
};

我就简单排了个序,感觉应该有更好的解法。

The Safest Way to Get what you Want is to Try and Deserve What you Want.
原文地址:https://www.cnblogs.com/Shinered/p/9726535.html