C++解题代码:
class Solutiion { public: bool isAnagram(string s, string t) { int *data = new int[26](); int n = s.length(); int m = t.length(); int temp; if(n!=m) return false; for(int i = 0; i < m; i++){ temp = s.at(i); data[temp - 'a']++; } for(int i = 0; i < n; i++){ temp = t.at(i); data[temp - 'a']--; if(data[temp - 'a'] < 0) return false; } return true; } }
Python3解题代码:
class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False def = {} for c in s: d[c] = d.get(c, 0) + 1 for c in t: d[c] = d.get(c, 0) - 1 if d[c] < 0: return False return True
class Solution: def isAnagram(self, s: str, t: str) -> bool: dic = {} for i in s: if i in dic: dic[i] += 1 else: dic[i] = 1 for i in t: if i not in dic or dic[i] <= 0: return False dic[i] -= 1 for i in dic: if dic[i] != 0: return False return True