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.
Example:
nput: 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".
식별자를 제외하고 로그를 문자와 숫자로 나누기 위해 끝자리를 비교해 리스트에 담고 문자 로그를 먼저 리스트에 넣어 출력하려고 했다. 문자가 동일할 경우 식별자 순으로 나열해야 하나.. 그 정렬 할 방법을 찾지 못하였다..
class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
letter_logs = []
digit_logs = []
# split digit and letter-logs
for log in logs:
if log[-1].isdigit():
digit_logs.append(log)
else:
letter_logs.append(log)
# need a process to order letter_logs
return letter_logs + digit_logs
풀이를 보니, 이를 문자열 로그 정렬을 하려면 람다 표현식을 사용하라고 한다. 그렇다.. 람다 표현식은 생각했지만, 어떻게 만들어야 할 지 구체적인 풀이가 떠오르지 않았다. 마지막에 람다 표현식 한 번 사용하니 바로 실행됐다. 각 잡고 람다 표현식도 정리 한번 해야할 것 같다.
# need a process to order letter_logs
letter_logs.sort(key=lambda x: (x.split()[1:], x.split()[0]))
'Study > problem solving' 카테고리의 다른 글
✓[LeetCode] 42. Trapping Rain Water (0) | 2023.03.03 |
---|---|
✓[LeetCode] 5. Longest Palindromic Substring (0) | 2022.11.28 |
[LeetCode] 49. Group Anagrams (0) | 2022.11.18 |
[LeetCode] 819. Most Common Word (1) | 2022.11.17 |
[LeetCode] 125. Valid Palindrome (0) | 2022.09.10 |