Leetcode 242. Valid Anagram (python+cpp)

Leetcode 242. Valid Anagram

  • 题目
  • 解析:

题目

Leetcode 242. Valid Anagram (python+cpp)_第1张图片

解析:

python:

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        
        counts = collections.defaultdict(int)
        
        for i in range(len(s)):
            counts[s[i]] += 1
            counts[t[i]] -= 1
        
        for _,count in counts.items():
            if count != 0:
                return False
        
        return True

C++

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

你可能感兴趣的:(Leetcode,字符串)