有效的字母异位词
题目
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的
字母异位词。
示例:
输入: s = “anagram”, t = “nagaram”
输出: true
思路
用一个大小为26的数组来统计a-z字符出现的次数,统计s中出现的字符次数,再减去t中出现的次数,若数组全为0,那么true
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public: bool isAnagram(string s, string t) { int count[26] = {0}; for(int i =0;i<s.size();i++){ count[s[i]-'a'] ++; } for(int i=0;i<t.size();i++){ count[t[i]-'a'] --; } for(int i=0;i<26;i++){ if(count[i]!=0) return false; } return true; } };
|