본문 바로가기
성장중/알고리즘 인터뷰

파이썬 알고리즘 인터뷰 p.148 로그 파일 재정렬

반응형

파이썬 알고리즘 인터뷰 p.148 로그 파일 재정렬

leetcode 937번

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

문제:

You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.

 

Example 1:
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".
class Solution:
    def reorderLogFiles(self, logs: List[str]) -> List[str]:
        let, dig = [], []
        
        for log in logs:
            if log.split()[1].isdigit(): # isdigit은 숫자인지를 판단해준다.
                dig.append(log)
            else:
                let.append(log)
                
        let.sort(key=lambda x: (x.split()[1:], x.split()[0]))
        return let + dig

logs에 저장된 내용물을 하나씩 꺼내서 1번째 인덱스에 숫자가 있으면 dig 리스트에 아니면 let 리스트에 추가한다.
람다 표현식을 사용해서 [0]에는 식별자가 있기에 [1:]을 키로 정렬 진행! 같다면 [0]로 정렬!

오늘도 혼자 고민해보다 결국은 이렇게 해답을 찾고서는 아! 이렇네요.
하다가 보면 늘겠죠!

화이팅!

반응형