1. 程式人生 > >LeetCode演算法題242:有效的字母異位詞解析

LeetCode演算法題242:有效的字母異位詞解析

給定兩個字串 s 和 t ,編寫一個函式來判斷 t 是否是 s 的一個字母異位詞。
示例 1:

輸入: s = "anagram", t = "nagaram"
輸出: true

示例 2:

輸入: s = "rat", t = "car"
輸出: false

說明:
你可以假設字串只包含小寫字母。

進階:
如果輸入字串包含 unicode 字元怎麼辦?你能否調整你的解法來應對這種情況?

字母異位詞就是字母的型別和數目都相同的詞,順序可以隨便。這個題簡單的思路就是用雜湊表來存每一個字母的出現次數,然後對照另一個字串的結果。還有一種就是既然只有26個小寫字母,可以使用一個數組代替,只要對應位置的數字符合就可以了。C++程式是使用陣列方法,python3程式使用了雜湊表。
C++原始碼:

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.length()!=t.length()) return false;
        vector<int> m(26, 0);
        for (int i=0;i<s.length();i++)
            m[s[i]-'a']++;
        for (int i=0;i<t.length();i++)
        {
            m[t[i]-'a']--;
            if
(m[t[i]-'a']<0) return false; } return true; } };

python3原始碼:

class Solution:
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s)!=len(t):
            return False
        m = {
} for i in range(len(s)): if s[i] in m.keys(): m[s[i]] += 1 else: m[s[i]] = 1 for i in range(len(t)): if t[i] in m.keys(): m[t[i]] -= 1 if m[t[i]] < 0: return False else: return False return True