LeetCode/Easy

937. Reorder Data in Log Files

GenieLove! 2022. 1. 23. 23:03
728x90
반응형

Go

import (
    "sort"
    "regexp"
)
func reorderLogFiles(logs []string) []string {
    r, _ := regexp.Compile(`^[0-9][0-9| ]*`)
    
    
    sort.SliceStable(logs, func(x, y int) bool {
        xExcept := strings.IndexAny(logs[x], " ") + 1
        yExcept := strings.IndexAny(logs[y], " ") + 1
        xisDigit := r.MatchString(logs[x][xExcept:])
        yisDigit := r.MatchString(logs[y][yExcept:])
        if (xisDigit && !yisDigit) || (!xisDigit && yisDigit) {
            return !xisDigit
        }
        
        if !xisDigit && !yisDigit {
            if logs[x][xExcept:] == logs[y][yExcept:] {
                return logs[x] < logs[y]
            }
            return logs[x][xExcept:] < logs[y][yExcept:]
        }
        
        return false
        
    })
    return logs
}

Python

from functools import cmp_to_key#앞 뒤 변수 비교
class Solution:
    def reorderLogFiles(self, logs: List[str]) -> List[str]:
        def sort_func(a: str, b: str):
            a_first_space = a.find(" ")
            b_first_space = b.find(" ")
            x = "".join(a.split(" ")[1:])
            y = "".join(b.split(" ")[1:])
            if (x.isdigit() and y.isalpha()) or (x.isalpha() and y.isdigit()):
                if x.isdigit():#x가 문자면 앞, 아니면 뒤
                    return 1
                return -1
            if x.isalpha() and y.isalpha():
                if a[a_first_space + 1:] == b[b_first_space + 1:]:
                    if a > b:
                        return 1
                    return -1
                else:
                    if a[a_first_space + 1:] > b[b_first_space + 1:]:
                        return 1
                    return -1
            return 1
        
        return sorted(logs, key=cmp_to_key(sort_func))

 

728x90
반응형