[LeetCode]242. Valid Anagram
来源:互联网 发布:淘宝助理ipad版 编辑:程序博客网 时间:2024/05/01 20:17
[LeetCode]242. Valid Anagram
题目描述
思路
1 hash map 对s中计数加,对t中计数减,结果不为0或者不存在的直接返回false
2 sort 直接排序后 返回 s == t ,效率最低
3 array, 初始化一个长度为26,值为0的数组,对字符串同时遍历,最后检查数组元素,有不为0的元素直接返回false
代码
#include<iostream>#include<string>#include<vector>#include<unordered_map>#include<algorithm>using namespace std;class Solution {public: bool isAnagram(string s, string t) { /* // unordered map if (s.size() > t.size()) swap(s, t); unordered_map<char, int> m; for (char ch : s) ++m[ch]; for (char ch : t) { if (m.count(ch) && m[ch] > 0) { --m[ch]; } else { return false; } } return true; */ /* //sort sort(s.begin(), s.end()); sort(t.begin(), t.end()); return s == t; */ //array if (s.size() != t.size()) return false; vector<int> counts(26, 0); for (int i = 0; i < s.size(); ++i) { counts[s[i] - 'a'] ++; counts[t[i] - 'a'] --; } for (int i = 0; i < 26; ++i) if (counts[i]) return false; return true; }};int main() { Solution s; cout << s.isAnagram("ab", "a") << endl; system("pause");}
0 0
- [leetcode] 242.Valid Anagram
- leetcode 242. Valid Anagram
- [leetcode] 242. Valid Anagram
- leetCode 242. Valid Anagram
- Leetcode 242. Valid Anagram
- 242. Valid Anagram LeetCode
- LeetCode 242. Valid Anagram
- LeetCode 242. Valid Anagram
- [LeetCode]242. Valid Anagram
- 【LeetCode】242. Valid Anagram
- leetcode 242. Valid Anagram
- leetcode 242. Valid Anagram
- LeetCode--242. Valid Anagram
- LeetCode *** 242. Valid Anagram
- #leetcode#242. Valid Anagram
- leetcode 242. Valid Anagram
- LeetCode 242. Valid Anagram
- 242.[LeetCode]Valid Anagram
- 二叉搜索树
- Spark Streaming + Kafka
- linux环境下项目启动
- 1016. Phone Bills (25)
- 《跨终端 Web》- 读书笔记(一)
- [LeetCode]242. Valid Anagram
- 紫书章四 习题4 Cube painting UVA
- 一篇文章教你如何协调投资理念跟量化模型的关系
- spark MLlib 学习
- intelliJ IDEA 编写邮箱注册功能报错 AddressException
- 在VirtualBox中使用Docker Machine管理主机
- 在BIOS中开启虚拟化技术
- Linux下安装PyCharm
- 1019. 数字黑洞 (20)-PAT乙级A1069