Leetcode 242. 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.

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

 

解决方法:

 用两个数组来记录每个字符串字符出现的次数,如何比较两个数组即可。

代码:

bool isAnagram(string s, string t) {
        if (s.size() != t.size())
            return false;
        
        int a[26] = {0}, b[26] = {0};
        for(int i = 0; i < s.size();i++){
            a[s[i] - 'a']++;
            b[t[i] - 'a']++;
        }
        
        for(int i = 0; i < 26; i++){
            if (a[i] != b[i])
                return false;
        }
        return true;
    }

 

发布了241 篇原创文章 · 获赞 0 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章