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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章