본문 바로가기

Algorithm/파이썬 알고리즘 인터뷰 스터디

[문자열 조작] 03 로그 파일 재정렬(Reorder Data in Log Files)

<LeetCode 문제>

https://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

주어지는 조건대로 정렬을 하는 문제입니다.

<풀이>

숫자로그는 입력 순서대로이므로 문자로그와 숫자로그를 구분하고, 숫자로그는 나중에 그대로 이어 붙이면 됩니다.

이때, 문자로그는 문자로그 내에서 정렬을 해주어야 하는데, content로 1차 비교, identifier로 2차 비교를 해서 정렬합니다.

이는 lambda함수를 통해 간단하게 작성할 수 있습니다.

class Solution:
    def reorderLogFiles(self, logs: List[str]) -> List[str]:
        digits=[] #digit-logs
        letters=[] #letter-logs
        
        for log in logs: #digit-log, letter-log나누기
            if log.split()[1].isdigit():
                digits.append(log)
            else:
                letters.append(log)
        
        #content로 1차비교, identifier로 2차비교 통해 정렬
        letters.sort(key=lambda x: (x.split()[1:], x.split()[0]))
                    
        return letters + digits #리스트 합치기

<학습내용>

1. lambda함수 구현(https://wikidocs.net/22804)

<학습이 필요한 내용>

1. map, reduce, filter 함수(https://wikidocs.net/64)

 

https://github.com/HoYoungChun/Algorithm_PS/blob/master/String/LC_937.py

 

GitHub - HoYoungChun/Algorithm_PS: Baekjoon Online Judge, Programmers, LeetCode problem solving by Python, C++

Baekjoon Online Judge, Programmers, LeetCode problem solving by Python, C++ - GitHub - HoYoungChun/Algorithm_PS: Baekjoon Online Judge, Programmers, LeetCode problem solving by Python, C++

github.com