[LeetCode] Valid Anagram
2015-08-01 14:14
435 查看
Hash Table
This idea uses a hash table to record the times of appearances of each letter in the two strings
The first implementation uses the built-in
Since the problem statement says that "the string contains only lowercase alphabets", we can simply use an array to simulate the
Sorting
For two anagrams, once they are sorted in a fixed order, they will become the same. This code is much shorter (this idea can be done in just 1 line using Python as here). However, it takes much longer time --- 76 ms in C++.
This idea uses a hash table to record the times of appearances of each letter in the two strings
sand
t. For each letter in
s, it increases the counter by
1while for each letter in
t, it decreases the counter by
1. Finally, all the counters will be
0if they two are anagrams of each other.
The first implementation uses the built-in
unordered_mapand takes 36 ms.
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; } };
Since the problem statement says that "the string contains only lowercase alphabets", we can simply use an array to simulate the
unordered_mapand speed up the code. The following implementation takes 12 ms.
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; } };
Sorting
For two anagrams, once they are sorted in a fixed order, they will become the same. This code is much shorter (this idea can be done in just 1 line using Python as here). However, it takes much longer time --- 76 ms in C++.
class Solution { public: bool isAnagram(string s, string t) { sort(s.begin(), s.end()); sort(t.begin(), t.end()); return s == t; } };
相关文章推荐
- mqtt的ClientSub
- 三个同步与互斥问题之生产者与消费者
- 机试算法讲解:第34题 并查集之求最短公路总长度
- JavaScript 如何计算2个时间差 工作时间为8小时
- 浅谈对java中的hashset和Treeset 中重写equals()方法的不同及用法
- mqtt的ClientPub
- 什么是MAK激活密钥?win10查看已激活Windows密钥Key的教程
- [python 爬虫学习]利用cookie模拟网站登录
- 2048游戏详解
- 那些低调的美国互联网金融公司
- svn服务器搭建
- java 中 try catch finally 语句的执行顺序
- qt学习第二课:建立链接
- 【Swift】学习笔记(七)——闭包
- java 基础知识 3
- C 你妹儿啊~~~~~~
- Subsequence
- 源代码管理SVN的使用
- CNN卷积神经网络推导和实现
- UIButton常用属性小结(编辑中。。。)