寫出一個(gè)函數(shù) anagram(s, t) 判斷兩個(gè)字符串是否可以通過(guò)改變字母的順序變成一樣的字符串。
您在真實(shí)的面試中是否遇到過(guò)這個(gè)題捎泻?
Yes
說(shuō)明
What is Anagram?
- Two strings are anagram if they can be the same after change the order of characters.
樣例
給出 s = "abcd",t="dcab"食侮,返回 true.
給出 s = "ab", t = "ab", 返回 true.
給出 s = "ab", t = "ac", 返回 false.
class Solution {
public:
/**
* @param s: The first string
* @param b: The second string
* @return true or false
*/
bool anagram(string s, string t) {
// write your code here
multiset<char> mset;
for(int i=0;i<s.length();i++){
mset.insert(s[i]);
};
for(int i=0;i<t.length();i++){
auto pos=mset.find(t[i]); //find 如果查找到的話爱谁,返回迭代器沟使,如果查找不到瓶蝴,返回指向end 的迭代器
if(pos==mset.end()){
//沒(méi)有找到
return false;
}
else{
mset.erase(pos);//
//mset.erase( cval ); // 不能這樣清除一個(gè)元素毒返,因?yàn)樗鼤?huì)清除掉所有的元素
}
}
return true;
}
};