Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram" Output: true
Example 2:
Input: s = "rat", t = "car" Output: 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?
My first solution:
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
s_size = len(s)
t_size = len(t)
if s_size != t_size:
return False
list_s = list(s)
list_t = list(t)
list_s.sort()
list_t.sort()
if list_s != list_t:
return False
return True
I use sort() method.
Second solution:
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
s_size = len(s)
t_size = len(t)
if s_size != t_size:
return False
anagram_dict = dict()
for string in s:
if string not in anagram_dict:
anagram_dict[string] = 1
else:
anagram_dict[string] += 1
for string in t:
if string not in anagram_dict:
return False
value = anagram_dict[string]
if value == 0:
return False
anagram_dict[string] -= 1
return True
I think second solution is more appropriate answer for coding interview.
'DataStructure > Strings' 카테고리의 다른 글
String to Integer (atoi) (0) | 2018.10.23 |
---|---|
Valid Palindrome (0) | 2018.10.23 |
First Unique Character in a String (0) | 2018.10.22 |
Reverse Integer (0) | 2018.10.22 |
Reverse String (0) | 2018.10.22 |