LeetCode.242.Valid Anagram

原題鏈接:Valid Anagram

題目內容:
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.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

給定兩個字符串,判斷是否是變位詞。默認只包含小寫字母。
引申:如果包含Unicode字符應該怎麼做


Python

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        def statistic(string):
            letters = [0 for i in range(0, 26)]
            if not string:
                return letters
            for letter in string:
                letters[ord(letter)-97] = letters[ord(letter)-97] + 1 
            return letters

        return statistic(s) == statistic(t)

C++

class Solution {
public:
    bool isAnagram(string s, string t) {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        return s == t;
    }
};
  • 排序之後判斷是否相等

Python.引申

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        def statistic(string):
            letters = dict()
            if not string:
                return letters
            for letter in string:
                if ord(letter)-97 not in letters:
                    letters[ord(letter)-97] = 0
                letters[ord(letter)-97] = letters[ord(letter)-97] + 1 
            return letters

        return statistic(s) == statistic(t)
  • ord函數可以接受unicode字符並轉化爲ascii碼
  • unicode字符多,不適用list格式,轉變爲dict以後,可以支持unicode字符,英文,標點等。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章