LeetCode string - valid alphabetic words

Effective alphabetic words

Given two strings s and t, write a function to determine whether t is an alphabetic word of s.

Example 1:

Input: S = anagram, t = nagaram
 Output: true

Example 2:

Input: S = rat, t = car
 Output: false

Explain:
You can assume that the string contains only lowercase letters.

Advance:
What if the input string contains unicode characters? Can you adjust your solution to deal with this situation?

Python:

My code 1:

1. Convert two strings into

   def isAnagram(s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        dic_s = {}
        dic_t = {}
        
        for char in s:
            if char in dic_s:
                dic_s[char] += 1
            else:
                dic_s[char] = 1
        for char in t:
            if char in dic_t:
                dic_t[char] += 1
            else:
                dic_t[char] = 1

        return operator.eq(dic_t,dic_s)
Code 2:

1. Judge string length
2. Throw it into the set to judge the length after two sets
3. Compare the number of characters

   def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False
        set_s = set(s)
        set_t = set(t)
        if len(set_s) != len(set_t):
            return False
        for char in set_s:
            if s.count(char) != t.count(char):
                return False
        return True

Code 3:
Character to ASCII

 def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        dic_s = {}
        dic_t = {}
        if len(s) != len(t):
            return False
        for char in s:
            if ord(char) in dic_s:
                dic_s[ord(char)] += 1
            else:
                dic_s[ord(char)] = 1
        for char in t:
            if ord(char) in dic_t:
                dic_t[ord(char)] += 1
            else:
                dic_t[ord(char)] = 1

        return operator.eq(dic_t,dic_s)

Keywords: Python ascii

Added by google_man2000 on Thu, 19 Dec 2019 22:22:59 +0200