一、题目
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?
题意:给定两个字符串s和t,看s和t是否是anagram。什么是anagram?就是s和t中元素需要一模一样,顺序可以不同
注意:由于两个字符串中的元素需要--对应,当两个字符串的长度不一致直接返回false
同时,字符串的的题字符集的范围,空字符串等情况。题目说只考虑小写字母的情况
思路:将s中元素放入map表中,遍历t的元素是否在表中,查找成功一次相应元素的值--。只要有一个元素不在就返回false
class Solution { public: bool isAnagram(string s, string t) { if(s.size()!=t.size()) return false; //unordered_map<char,int> maps; //hash表实现的效率反而更低? map<char,int> maps; for(auto temps:s) { maps[temps]++; } for(auto tempt:t) { if(maps[tempt]) { maps[tempt]--; } else { return false; } } return true; } };