[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?

代码:

#include<map>
using namespace std;
static int x = []() { 
    std::ios::sync_with_stdio(false); 
    cin.tie(NULL);  
    return 0; 
}();
class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size() != t.size()) return false;
        map<char, int> m;
        for(int i = 0; i < s.size(); i++){
            if(m.find(s[i]) == m.end()){
                m[s[i]] = 1;
            }else{
                m[s[i]]++;
            }
        }
        for(int i = 0; i < t.size(); i++){
            if(m.find(t[i]) == m.end()){
                return false;
            }else{
                if(m[t[i]] == 0) return false;
                else m[t[i]]--;
            }
        }
        return true;
    }
};


猜你喜欢

转载自blog.csdn.net/jing16337305/article/details/80237908