ZhongKuo0228 / study

0 stars 0 forks source link

242. Valid Anagram #24

Open ZhongKuo0228 opened 1 year ago

ZhongKuo0228 commented 1 year ago

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Constraints:

1 <= s.length, t.length <= 5 * 104 s and t consist of lowercase English letters.

https://leetcode.com/problems/valid-anagram/description/

ZhongKuo0228 commented 1 year ago

將字串轉換為陣列,排序,再轉換回字串,時間複雜度是 n logn?

var isAnagram = function(s, t) {

    let sorted_s = s.split('').sort().join('');
    let sorted_t = t.split('').sort().join('');

    if(sorted_s === sorted_t){
        return true;
    }

    return false;

};
ZhongKuo0228 commented 1 year ago

使用python的字典來儲存每個字串內的字母出現次數,再將兩個在字典做比較, python的字典是看key value是否相同,跟順序無關

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        #將s的每個單字存成dic結構,並計算每個單字出現的次數
        s_dic = {}
        for letter in s:
            if letter in s_dic:
                s_dic[letter] +=1
            else:
                s_dic[letter] = 1

        #將t的每個單字存成dic結構,並計算每個單字出現的次數
        t_dic = {}
        for letter in t:
            if letter in t_dic:
                t_dic[letter] +=1
            else:
                t_dic[letter] = 1

        #比較兩個dic是否相同
        if s_dic == t_dic:
            return True
        else:
            return False