【Sort】242. Valid Anagram
来源:互联网 发布:c语言编程器下载 编辑:程序博客网 时间:2024/05/01 20:47
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?
AC代码:
class Solution {public: bool isAnagram(string s, string t) { unordered_map<int,int> map; unordered_map<int,int>::iterator it; int len1=s.length(); int len2=t.length(); if(len1!=len2) return false; for(int i=0;i<len1;i++){ map[s[i]-'a']++; map[t[i]-'a']--; } for(it=map.begin();it!=map.end();it++) if((it->second)!=0) return false; return true; }};
这是人家的哈希表,优雅多了。。。哎。。。自己还是很菜啊,不熟悉C++的STL
class Solution {public: bool isAnagram(string s, string t) { if (s.length() != t.length()) return false; int n = s.length(); unordered_map<char, int> counts; for (int i = 0; i < n; i++) { counts[s[i]]++; counts[t[i]]--; } for (auto count : counts) if (count.second) return false; return true; }};事实上用数组就可以办到了:
class Solution {public: bool isAnagram(string s, string t) { if (s.length() != t.length()) return false; int n = s.length(); int counts[26] = {0}; for (int i = 0; i < n; i++) { counts[s[i] - 'a']++; counts[t[i] - 'a']--; } for (int i = 0; i < 26; i++) if (counts[i]) return false; return true; }};
然后当然最直接的方法是给两个数组排序,然后比较一下一不一样,啊哈哈哈。但是耗时肯定很长了=。=
阅读全文
0 0
- 【Sort】242. Valid Anagram
- [LeetCode]--242. Valid Anagram(Count table && char array sort())
- [leetcode] 242.Valid Anagram
- 242.Valid Anagram
- leetcode 242. Valid Anagram
- 242. Valid Anagram
- [leetcode] 242. Valid Anagram
- leetCode 242. Valid Anagram
- Leetcode 242. Valid Anagram
- 242. Valid Anagram
- 242. Valid Anagram LeetCode
- 242. Valid Anagram
- LeetCode 242. Valid Anagram
- LeetCode 242. Valid Anagram
- 242. Valid Anagram
- 242. Valid Anagram
- 242. Valid Anagram
- 242. Valid Anagram
- Codeforces 702D Road to Post Office(模拟 + 公式推导)
- 郑州集训DAY3笔记
- css学习-2017.10.7
- C++入门
- 2017.10.07【NOIP提高组】模拟赛B组 Heatwave 题解
- 【Sort】242. Valid Anagram
- 360加速球效果实现
- Html+JavaScript+百度地图api:GPS功能单点运动
- (POJ 1949)Chores DAG简单DP
- 前端定位 元素 列表显示
- 深度学习: 验证集 & 测试集 区别
- linux设置串口固定
- 去哪儿笔试:统计字符
- 两个超经典怀旧版但宝刀未老的迷你迅雷和迅雷精简版分享 万千感慨 感动到哭