[Easy] 242. Valid Anagram

242. Valid Anagram

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true
Example 2:

Input: s = "rat", t = "car"
Output: false

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

Solution

Hash Table

Runtime: 32 ms, faster than 41.57% of C++ online submissions for Valid Anagram.
Memory Usage: 7.4 MB, less than 100.00% of C++ online submissions for Valid Anagram.

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size()!=t.size()) return false;
        unordered_map<char, int> map;
        for(int i = 0; i < s.size(); i++){
            map[s[i]-'a']++;
            map[t[i]-'a']--;
        }
        for(auto it = map.begin(); it != map.end(); it++){
            if(it->second != 0) return false;
        }
        return true;
    }
};
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读