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.
cpp:
class Solution { public: bool isAnagram(string s, string t) { if(s.size() != t.size()) return false; int n=s.size(); vector<int> counts(26, 0); for(int i=0; i<n; i++) { counts[s[i]-97]++; counts[t[i]-97]--; } for(auto count:counts) if(count) return false; return true; } };
python:
class Solution(object): def isAnagram(self,s,t): listA = [0]*26 if len(s) != len(t): return False elif s == '' and t =='': return True else: for i in range(0,len(s)): listA[ord(s[i])-97] += 1 listA[ord(t[i])-97] -= 1 for i in range(0,26): if listA[i]!= 0: return False return True