- Date : 2022.02.27(월)
- Time : 40분
- You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.
- There are two types of logs:
- Letter-logs: All words (except the identifier) consist of lowercase English letters.
- Digit-logs: All words (except the identifier) consist of digits.
- Reorder these logs so that:
- The letter-logs come before all digit-logs.
- The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
- The digit-logs maintain their relative ordering.
- Return the final order of the logs.
- 1 <= logs.length <= 100
- 3 <= logs[i].length <= 100
- All the tokens of logs[i] are separated by a single space.
- logs[i] is guaranteed to have an identifier and at least one word after the identifier.
- Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
- Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]
- Explanation: The letter-log contents are all different, so their ordering is "art can", "art zero", "own kit dig".The digit-logs have a relative order of "dig1 8 1 5 1", "dig2 3 6".
def reorderLogFiles(self, logs: List[str]) -> List[str]:
digit_logs_stack = []
letter_logs_stack = []
for log in logs:
t = log.split()
identifier, logs = t[0], ' '.join(t[1:])
if logs[0].isdigit():
digit_logs_stack.append(log)
else:
letter_logs_stack.append((identifier, logs))
letter_logs_stack.sort(key=lambda x: (x[1],x[0]))
return [f'{x} {y}' for x,y in letter_logs_stack] + digit_logs_stack: 이 문제는 배열을 정렬해주는 문제! 배열을 보면 문자 숫자가 띄어쓰기로 구분되어 있는데 [a b c]를 예로 들어보면 맨 처음 a는 식별자, b와 c는 단어이다. 이제 여기서 b,c가 문자이면 Letter-logs, 숫자이면 Digit-log이다. 로그에 정렬 순서는 먼저 모든 문자 로그는 숫자 로그보다 높은 순위이다. 그렇기 때문에 두개를 따로 계산해준 뒤에 숫자 로그를 문자 로그 뒤에 더해주는 방식을 택했다. 이제 문자로그는 사전순으로 정렬를 해주면 된다. 하지만 먼저 로그끼리 대결을 한 후에 로그가 똑같다면 앞의 식별자로 비교해주는 방식을 택한다. 그렇기 때문에 sort에서 lambda를 통해 x[1]부터 비교해준 후 그 다음에 식별자인 x[0]을 비교해주었다.