LeetCode Valid Anagram
来源:互联网 发布:淘宝网聚划算首页 编辑:程序博客网 时间:2024/05/11 17:15
LeetCode Valid Anagram
题目
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
思路&代码
对于只有小写字母的情况,只需要开一个26个int大小的数组对两个字符串进行字母统计即可,对一个字符串加而对另一个字符串减。这样,如果最后统计数组有一个字符次数不为0,即可知道不一样。
class Solution {public: bool isAnagram(string s, string t) { int charNums[26]; memset(charNums, 0, sizeof(charNums)); for (int i = s.size() - 1; i >= 0; i--) charNums[s[i] - 'a']++; for (int i = t.size() - 1; i >= 0; i--) { charNums[t[i] - 'a']--; if (charNums[t[i] - 'a'] < 0) return false; } for (int i = 0; i < 26; i++) if (charNums[i]) return false; return true; }};
但是,如果字符有可能包含Unicode字符,也就是有65536个字符的情况下,当然我们思路也是一样,也可以使用数组来统计。但是这样就会造成极大的空间浪费,所以我选择牺牲时间而节约空间使用map来统计,时间上大概增加了100ms(仅在此题中)。
class Solution {public: bool isAnagram(string s, string t) { map<char, int> hash; for (int i = s.size() - 1; i >= 0; i--) { if (hash.find(s[i]) == hash.end()) hash[s[i]] = 1; else hash[s[i]]++; } for (int i = t.size() - 1; i >= 0; i--) { if (hash.find(t[i]) == hash.end()) return false; else hash[t[i]]--; } for (map<char, int>::iterator iter = hash.begin(); iter != hash.end(); iter++) if (iter->second != 0) return false; return true; } };
0 0
- Leetcode #242 Valid Anagram
- leetcode-242-Valid Anagram
- Leetcode: Valid Anagram
- 【leetCode】Valid Anagram
- [leetcode] 242.Valid Anagram
- leetcode 242: Valid Anagram
- 【leetcode】Valid Anagram
- [leetcode] Valid Anagram
- LeetCode Valid Anagram
- 【LeetCode】242 Valid Anagram
- [LeetCode] Valid Anagram
- leetcode: Valid Anagram
- leetCode(53):Valid Anagram
- leetcode Valid Anagram 异位体
- [leetcode 242]Valid Anagram
- leetcode Valid Anagram
- leetCode #242 Valid Anagram
- LeetCode题解:Valid Anagram
- 解决服务器不支持json
- Python 绘制 误差 箱线图 error boxplot
- 文章标题
- Spark PageRank
- Hello, Android 深入(二)
- LeetCode Valid Anagram
- 如何通过html上传照片(自定义上传图标)
- redis基本数据类型
- [LeetCode246] Strobogrammatic Number
- 【VSTS 日志】VSTS 所有功能,看这个页面就够了!
- 创建视图时with check option问题
- kafka入门:简介、使用场景、设计原理、主要配置及集群搭建(转)
- leetcode 19 :Remove Nth Node From End of List
- iOS中键盘操作