[leetcode] Valid Anagram


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.

use sort

class Solution {
public:
    bool isAnagram(string s, string t) {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        return s == t;
    }
};

 

 

use a hashmap

class Solution {
public:
    bool isAnagram(string s, string t) {
        unordered_map<char, int> maps;
        for(char c : s){
            if(maps.find(c) == maps.end()){
                maps[c] = 1;
            }
            else{
                maps[c]++;
            }
        }
        for(char c : t){
            if(maps.find(c) == maps.end()){
                return false;
            }
            maps[c]--;
            if(maps[c] == 0) maps.erase(c);
        }
        if(maps.size() > 0) return false;
        return true;
    }
};

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.