【一天一道LeetCode】#242. Valid Anagram
2016-07-13 21:17
357 查看
一天一道LeetCode
本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处
(一)题目
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,判断t是不是s的有效字谜解题思路:有效字谜是指t是由s中的字符改变相对位置后组成的字符串。
84ms解题版本:
class Solution { public: bool isAnagram(string s, string t) { if(s.length()!=t.length()) return false;//长度不等,直接返回false sort(s.begin(),s.end());//排序 sort(t.begin(),t.end()); return s==t?true:false;//判断是否相等 } };
12ms的版本:
用哈希表,首先遍历s,记录每个字符出现的次数,然后遍历t,出现某个字符就次数就减1,判断最后的次数是否都为0
class Solution { public: bool isAnagram(string s, string t) { int count[26] = {0}; for(int i = 0 ; i < s.length();i++) count[s[i]-'a']++; for(int i = 0 ; i < t.length();i++) count[t[i]-'a']--; for(int i = 0 ; i < 26 ; i++) if(count[i]!=0) return false; return true; } };
相关文章推荐
- 【一天一道LeetCode】#171. Excel Sheet Column Number
- .NET微信自定义分享标题、缩略图、超链接及描述的设置方法
- POJ3984(迷宫问题)
- Python的图形化界面
- 最大流最小割问题的流量计算问题
- Redis数据库(set类型和zset类型)
- 关于本地连接远程github仓库的若干问题
- android webview快速获取页面上的图片
- Git(二)
- 获取网页中的视频下载地址(利用proxy_server)
- js事件处理(DOM0,DOM2,IE)
- netty学习(三)——开始传送对象喽!!
- hdu 5142(数学-进制转换)
- RT-Thread创建静态、动态线程
- 链表的头结点和尾节点的用处
- SearchView简单示例
- Python+Selenium+PIL+Tesseract真正自动识别验证码进行一键登录
- 最优配对问题
- 欢迎使用CSDN-markdown编辑器
- Day three