您的位置:首页 > 编程语言 > C语言/C++

[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 C++ 242 Anagram Valid