[LeetCode]242. Valid Anagram(有效字谜)
2017-04-21 21:21
183 查看
242. Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.给定两个字符串s和t,写一个函数来确定t是否是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.
(假定只有小写字母)
其实就是判断第一个字符串和第二个字符串是否包含同样的字母,顺序不一样而已
思路:
第一反应用异或,用了好多例子回忆异或
将字符串排序,比较各个位置上字母是否相同(排序导致效率低下)
代码如下:
#include <iostream> #include <string> #include<algorithm> using namespace std; class Solution { public: bool isAnagram(string s, string t) { if(s.size() != t.size())//判断两个字符串长度是否相同 return false; if(s.size() == 0)//判断两个字符串长度是否为空 return true; sort(s.begin(), s.end());//将两个字符串排序 sort(t.begin(), t.end()); bool res; for(int i=0; i<s.size(); i++){ res = s[i]^t[i];//相同为0 不同为1 if(res == 1) return false; } return true; } }; int main() { //0 false; 1 true //异或 相同为0 不同为1 /* char a0 = 'a'; char a1 = 'b'; char a2 = 'a'; bool b = a0^a1;//1 bool类型 int b1 = a0^a1;//3 int类型 bool c = a0^a2;//0 bool d = (a0^a1)^(a1^a0);//0 b ^= (a1^a0);//1 b1 ^= (a1^a0);//0 cout << b << c << d << b1<< endl;//1 0 0 0 */ Solution a; string s = "aa"; string t = "bb"; string s1 = "ab"; string t1 = "ba"; cout << a.isAnagram(s, t) << endl; cout << a.isAnagram(s1, t1) << endl; return 0; }
写完之后才发现,根本不用比较一个个的字符,排序后两字符串应该完全相同,直接比较字符串就行。贴出代码:
class Solution { public: bool isAnagram1(string s, string t) { sort(s.begin(), s.end()); sort(t.begin(), t.end()); return (s == t); } };
随后又想出来一个方法,定义一个数组counts来存储各个字母数量(默认值为0),字符串s增加各个字母数量,字符串t减少各个字母数量,最后判断数组counts是否每个元素都是0,只要有一个元素不为0,返回false,否则返回true,贴出代码:
bool isAnagram2(string s, string t) { if(s.size() != t.size())//判断两个字符串长度是否相同 return false; int counts[26] = {0}; for(int i=0; i<s.size(); i++){ counts[s[i]-'a']++; counts[t[i]-'a']--; } for(int m=0; m<26; m++){ if(counts[m])//counts[m]!=0 return false; } return true; }
在网上看到了一个利用Hash Table的方法,思路大致相同
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; } };
相关文章推荐
- LeetCode 242 Valid Anagram(有效字谜)(*)
- leetcode 242 有效的字母异位词
- LeetCode Valid Sudoku 有效数独
- leetcode-65-有效的数字
- [leetcode]20. Valid Parentheses ,有效的括号符串python实现【easy】
- 20. 有效的括号-leetcode
- leetCode 36.Valid Sudoku(有效的数独) 解题思路和方法
- leetcode 468. Validate IP Address 有效的IP检查 IPV4和IPV6地址的检查和区分
- leetcode 367. Valid Perfect Square有效的完全平方数
- LeetCode | Validate Binary Search Tree(有效的二叉搜索树)
- 每天一道LeetCode-----有效回文串
- Leetcode:Generate Parentheses 生成有效括号对
- 【LeetCode刷题】有效的括号字符串Valid Parentheses(java)
- [leetcode]Valid Sudoku(判断有效数独 C语言实现)
- Valid Anagram 有效的字谜
- leetCode 98.Validate Binary Search Tree (有效二叉搜索树) 解题思路和方法
- LeetCode | Valid Palindrome(有效的回文串)
- leetcode上做的一道判断括号字符串是否有效的问题
- leetcode--22--产生有效括号
- [LeetCode]39. Longest Valid Parentheses最长有效括号对