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.
思路:统计各字符串中字母出现的次数;然后比较次数;
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#define MAXN 300+10
using namespace std;
bool isAnagram(string s, string t) {
int slength = s.size();
int tlength = t.size();
int k = 0;
int A[26] = {0};
int B[26] = {0};
if( slength != tlength)
return 0;
else{
for(int i = 0; i < slength; i++)
A[s[i] - 'a']++;
for(int j = 0; j < tlength; j++)
B[t[j] - 'a']++;
for(int i = 0; i < 26; i++){
if( A[i] == B[i])
k++;
}
if( k == 26)
return 1;
else
return 0;
}
}
int main()
{
string s, t;
bool a;
cin >> s;
cin >> t;
a = isAnagram(s, t);
cout << a;
cout << endl;
}
https://leetcode.com/submissions/detail/38612737/
*另外
下面这串代码
思路为:用string s中的字母逐一在string t中寻找相同的字母,找到后将其从string t中剔除,判断最后t中是否剩余的字母,决定string s 与 string t是否相等;
在submit solution时出现time limit exceeded;
还不能解决问题!!
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#define MAXN 300+10
using namespace std;
bool isAnagram(string s, string t) {
int slength = s.size();
int tlength = t.size();
int L = tlength;
for(int i = 0; i < slength; i++)
{
for(int j = 0; j < tlength; j++)
{
if( s[i] == t[j])
{
for(int x = j; j < L-1; j++)
{
t[j] = t[j+1];
}
t[L-1] = '0';
L--;
break;
}
}
}
if(L == 0 && slength == tlength)
return 1;
else
return 0;
}
int main()
{
string s, t;
bool a;
cin >> s;
cin >> t;
a = isAnagram(s, t);
cout << a;
cout << endl;
}