题目:
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.
翻译:
给定两个字符串 s 和 t, 写下一个函数来判断 t 是否为 s 的一个字谜。
举例,
s = "anagram", t = "nagaram", 返回真。
s = "rat", t = "car", 返回假。
注意:
你可以假设字符串中值包含小写字母。
思路:
首先要明确什么叫做作 t 是 s 的字谜。这里的字谜是要求字符串 t 的长度和 s 相等,并且,t 中含有和 s 中同样的字符,并且每一类字符的数量也要求相等。于是想到用 map 映射来解决,s 中出现的字符数量加一,同时若 t 中也出现同样的字符则作减一操作,最后,通过判断 map 中各字符的数量来判断 t 是否为 s 的字谜,若是,则 map 中所有字符数为0,返回 true,否则,返回 false。
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size())
return false;
unordered_map<char, int> m;
for (int i = 0; i < s.size(); i++) {
m[s[i]]++;
m[t[i]]--;
}
for (int i = 0; i < s.size(); i++) {
if (m[s[i]] != 0)
return false;
}
return true;
}
};
int main()
{
Solution s;
bool result;
string p="ccac";
string t = "acca";
result = s.isAnagram(p, t);
cout << result;
return 0;
}