반응형
문제 링크 : leetcode.com/problems/reorder-data-in-log-files/
Reorder Data in Log Files - 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
로그가 str인 리스트로 주어지고 str에 " "가 delimiter 다. 두 번째 값으로 정렬하는데 문자가 숫자보다 우선이다. 또한 숫자는 문자의 뒤로만 보낼뿐 정렬하지 않는다. 문자 정렬의 경우 앞의 identifier로 정렬한다. (이부분이 확실치가 않다)
리스트 컴프리헨션으로 풀려다가 말아먹고 책을 살짝 봤다. 그 후에도 30분 정도 걸렸는데 sort하는 key를 lambda x: (x.split(" ")[1], x.split(" ")[0]))
으로 했더니 틀렸다.
지금 보니 split
할 때 default
가 " "
이다. None (the default value) means split according to any whitespace
class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
digit = []
alpha = []
for log in logs:
if log.split(" ")[1].isdigit():
digit.append(log)
else:
alpha.append(log)
alpha.sort(key=lambda x: (x.split(" ")[1:], x))
return alpha + digit
좀 더 깨끗한 답은 아래다.
class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
digit, alpha = [], []
for log in logs:
if log.split()[1].isdigit():
digit.append(log)
else:
alpha.append(log)
alpha.sort(key=lambda x: (x.split()[1:], x.split()[0]))
return alpha + digit