Lintcode:兩個字符串是變位詞

問題:

寫出一個函數 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?

  • 在更改字符順序後兩個字符串可以相同

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章