본문 바로가기

알고리즘 문제풀이/[Python] LeetCode

[LeetCode 49번] Group Anagrams - (문자열 처리)

https://leetcode.com/problems/group-anagrams/

 

Group Anagrams - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

입력된 여러 문자열들을 Anagram끼리 묶어서 return해주는 함수를 짜는 문제이다.

 

def groupAnagrams(strs):
  info,result=[],[]
  print(result)
  for str in strs:
    info.append([char for char in str])
  for i in info:
    i.sort()
  length=len(info)
  check=[0 for _ in range(length)]
  for i in range(length):
    if check[i]!=0: 
      continue
    result.append([strs[i]])
    tmp=result.index([strs[i]])
    check[i]+=1
    for j in range(i+1,length):
      if check[j]!=0: 
        continue
      if info[i]==info[j]:
        result[tmp].append(strs[j])
        check[j]+=1
  if result==[]:
    return [['']]
  return result

처음에는 이렇게 말도안되게 긴 코드를 노가다로 작성했다.

물론 Accept를 받기는 했는데 코드 실행시간이 말도안되게 길었다.

 

내가 이 문제에서 활용하지 못한 pythonic한 방법이 2가지가 있다.

 

  1. collections모듈에 있는 defaultdict !!
  2.  join 함수를 이용한 문자열과 리스트의 적절한 변환 

defaultdict 함수는 여기 에서 추가적으로 설명하도록 하겠다.

 

이 두가지 방법을 이용해서 아래처럼 아주 간단한 코드를 완성했다.

 

def groupAnagrams(strs):
  result=defaultdict(list)
  for str in strs:
    result[''.join(sorted(list(str)))].append(str)
  	# result[''.join(sorted(str))].append(str)
  return list(result.values())

 

 

sorted함수는 list에서만 사용 가능한것이 아니라 문자열에서도 사용 가능하다.

위의 주석처럼 sorted(str)을 하면 아래의 예시처럼 각 알파벳이 정렬된 리스트가 반환된다.

str="bacd"
print(sorted(str))

>>['a','b','c','d']