問題:
寫出一個函數 anagram(s, t)
判斷兩個字符串是否可以通過改變字母的順序變成一樣的字符串。
樣例:
樣例 1:
輸入: s = "ab", t = "ab" 輸出: true
樣例 2:
輸入: s = "abcd", t = "dcba" 輸出: true
樣例 3:
輸入: s = "ac", t = "ab" 輸出: false
python:
class Solution:
"""
@param s: The first string
@param t: The second string
@return: true or false
"""
def anagram(self, s, t):
# write your code here
return sorted(s) == sorted(t)
C++:
class Solution {
public:
/**
* @param s: The first string
* @param t: The second string
* @return: true or false
*/
bool anagram(string &s, string &t) {
// write your code here
if(s.size() != t.size())
{
return false;
}
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
PS:什麼是 Anagram?
- 在更改字符順序後兩個字符串可以相同