LeetCode 242. Valid Anagram
[26]位数组,存储对应字母出现的个数,s、t分别得到不同数组,比较两个数组是否相同。
1 class Solution { 2 public: 3 bool isAnagram(string s, string t) { 4 if(s.length() != t.length()) return false; 5 int s_data[26] = {}, t_data[26] = {0}; 6 for(int i = 0; i < s.length(); ++i){ 7 s_data[s[i] - '0' - 49] += 1; 8 t_data[t[i] - '0' - 49] += 1; 9 } 10 for(int i = 0; i < 26; ++i){ 11 if(s_data[i] != t_data[i]) return false; 12 } 13 return true; 14 } 15 };
python一行写法(调用库函数):
1 class Solution(object): 2 def isAnagram(self, s, t): 3 return sorted(s) == sorted(t)
c++ 相同思路 不同写法:
1 class Solution { 2 public: 3 bool isAnagram(string s, string t) { 4 if(s.size() != t.size()) return false; 5 int n=s.size(); 6 vector<int> counts(128, 0); 7 for(int i=0; i<n; i++) 8 { 9 counts[s[i]]++; 10 counts[t[i]]--; 11 } 12 for(auto count:counts) 13 if(count) return false; 14 return true; 15 } 16 };

浙公网安备 33010602011771号