LeetCode (54) Valid Anagram
阿新 • • 發佈:2019-01-12
題目描述
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.
題目要求判斷兩個string是否具有相同的字母(包括字母出現的次數)。
解題思路
我們可以遍歷字串s,逐一判斷s中的字母是否在t中,若在,則刪除改字母。若t中查詢不到該字母,則返回false;若s遍歷完後t不為空,則也返回false,否則返回true。
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size()) return false;
for(string::iterator it=s.begin(); it != s.end(); ++it)
{
int pos = t.find_first_of(*it);
if (pos == string::npos)
return false;
else
t.erase(pos, 1);
}
if(t.empty()) return true;
else return true;
}
};