프로그래밍/LeetCode
[LeetCode][Python3] 242. Valid Anagram
snoopybox
2018. 11. 4. 21:51
Problem :
https://leetcode.com/problems/valid-anagram/
My Solution :
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return sorted(s) == sorted(t)
Comment :
위 풀이는 그냥 장난이고... 위처럼 정렬을 이용하면 O(nlogn)으로 2pass 걸리고 다시 비교하는데 O(n)이 소요된다. 따라서 아래와 같이 풀어야 더 효율적인데, 알파벳 소문자라고 했기 때문에 그냥 List를 사용하였다. Unicode라면 Dictionary를 활용하면 된다.
My Solution2 :
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
counter = [0]*26
for c in s:
counter[ord(c)-97] += 1
for c in t:
if counter[ord(c)-97] == 0:
return False
counter[ord(c)-97] -= 1
return True