242. Valid Anagram
2015-11-28 15:47
393 查看
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;
}
};
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;
}
};
相关文章推荐
- CSDN《老友记》简记
- erlang R16B02 服务器进程消失问题
- androguard&yara
- 用java读写properties文件的代码
- “南大软院大神养成计划“_第十三天的学习“
- 啊Ran讲微信开发(.net) 目录结构
- 微信书的分月存储
- 1-3-11:计算浮点数相除的余数
- 寄存器 之 SI DI
- mysql 1292 错误
- collectd简介
- 杭电1592 Half of and a Half 大数
- 选项卡控件(TabControl)的操作
- IIS MVC 发布错误 403.14-Forbidden Web 服务器被配置为不列出此目录的内容
- 使用new char[]遇到过的几个坑
- Java注解知识点整理
- hashMap的再认识
- PHP函数操作数组(集合贴)
- NOIP2015总结
- iOS开发:在Xcode中用Pods管理第三方库