【LeetCode从零单刷】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.

解答:

不要被各种类型的移形换位所迷惑,不论如何更换位置,各种字母出现的次数都是相同的。

class Solution {
public:
    bool isAnagram(string s, string t) {
        int lens = s.length();
        int lent = t.length();
        
        if(lens != lent)    return false;
        map<char, int> tmps, tmpt;
        tmps.clear();
        tmpt.clear();
        for(int i=0; i< lens; i++)
        {
            tmps[s[i]] ++;
            tmpt[t[i]] ++;
        }
        
        for(char j='a'; j<='z'; j++)
        {
            if(tmps[j] != tmpt[j])  return false;
        }
        return true;
    }
};

你可能感兴趣的:(LeetCode,C++)