LeetCode探索の旅(70)-242有効な変位


引き続きLeetCode,242題をブラシし,2つの文字列が有効な変位であるか否かを判断し,1つの文字列のアルファベットをシフトする.
分析:方法1:転位だけである以上、2つの文字列を並べ替えて、2つの文字列が等しいかどうかを比較することができます.方法2:各アルファベットの出現回数を統計し、最後に2つの文字列のアルファベットの出現回数が等しいかどうかを比較し、ずれているかどうかを判断する.
問題:1、問題を審査するには注意しなければならない.
C++コード1を添付します.
class Solution {
public:
    bool isAnagram(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;
        else
            return false;
        
    }
};

C++コード2を添付します.
class Solution {
public:
    bool isAnagram(string s, string t) {
        vector temp(26,0);
        if(s.length()!=t.length())
            return false;
        for(int i=0;i

Pythonコード1を添付します.Runtimeは84 msです.
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if sorted(s)!=sorted(t):
            return False
        else:
            return True

Pythonコード2を添付し、Runtimeは40 ms:
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s)!=len(t):
            return False
        for word in set(s):
            if s.count(word)!=t.count(word):
                return False
        return True