题目: 给定两个字符串s和t,编写一个函数来判断t是否是s的字母异位词。
注:若s和t中每个字符出现的次数都相同,则称s和t互为字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
示例 2:
输入: s = "art", t = "ant
输出: false
解析: 新进行字符串排序,在进行字符串比较
实例源码:
// len12.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
#include <algorithm>
using namespace std;
bool IsAnagram(string s, string t)
{
if (s.size() != t.size())
{
return false;
}
// 对字符串s,t分别进行排序
sort(s.begin(), s.end());
sort(t.begin(), t.end());
// 比较字符串
if (strcmp(s.c_str(), t.c_str()) != 0)
{
return false;
}
return true;
}
void PrintStr(string s1, string s2, int nResult)
{
printf("\ns1=\"%s\"", s1.c_str());
printf("\ns2=\"%s\"", s2.c_str());
printf("\nnResult=\"%s\"\n", (nResult!=0)?("true"):("false"));
}
int _tmain(int argc, _TCHAR* argv[])
{
string s1 = "anagram";
string s2 = "nagaram";
int nResult = IsAnagram(s1, s2);
PrintStr(s1, s2, nResult);
s1 = "rat";
s2 = "car";
nResult = IsAnagram(s1, s2);
PrintStr(s1, s2, nResult);
s1 = "art";
s2 = "ant";
nResult = IsAnagram(s1, s2);
PrintStr(s1, s2, nResult);
return 0;
}
执行结果: