242. Valid Anagram

来源:互联网 发布:java rpc客户端 编辑:程序博客网 时间:2024/05/09 22:57

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?

Subscribe to see which companies asked this question

Hide Tags
 Hash Table Sort
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss

相同字母异序词。

首先,若二者长度不等,直接返回false;

哈希表,char做key,int做value,记录s中char出现的次数。

对于t中出现的字母,首先在哈希表中查找,如果找不到则直接返回false;如果找得到则将其value值减1,若value值小于0,则直接返回false。

最后遍历哈希表,检查value值是否均为0,若有不为0的,直接返回false;否则返回true;

class Solution {public:    bool isAnagram(string s, string t) {                if(s.length() != t.length())            return false;        unordered_map<char,int> charMap;        for(int i = 0;i<s.length();++i)        {            ++charMap[s[i]];            --charMap[t[i]];        }                for(unordered_map<char,int>::iterator it = charMap.begin();it!= charMap.end();++it)        {            if(it->second)                return false;        }                return true;            }};


0 0
原创粉丝点击