題目: 給定兩個字符串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;
}
執行結果: