본문 바로가기
LeetCode/Problems

LeetCode 937. Reorder Data in Log Files

by 벤진[Benzene] 2020. 8. 17.

Problem:

You have an array of logs.  Each log is a space delimited string of words.

For each log, the first word in each log is an alphanumeric identifier.  Then, either:

  • Each word after the identifier will consist only of lowercase letters, or;
  • Each word after the identifier will consist only of digits.

We will call these two varieties of logs letter-logs and digit-logs.  It is guaranteed that each log has at least one word after its identifier.

Reorder the logs so that all of the letter-logs come before any digit-log.  The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties.  The digit-logs should be put in their original order.

Return the final order of the logs.

 

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"]

 

-Summary-

1. Create two lists to save the data of log depends on the letter-logs and digit-logs.

2. Sort the letter list by using lambda expression and sort function with a key.
3. Make letter-logs and digit-logs list together

 

-Code-

class Solution:
    def reorderLogFiles(self, logs: List[str]) -> List[str]:
        letters_logs, digit_logs = [], []
        
        for log in logs:
            if log.split()[1].isdigit():
                digit_logs.append(log)
            else:
                letters_logs.append(log)
        
        letters_logs.sort(key = lambda x: (x.split()[1:], x.split()[0]))
        '''
        if lambda function not used:
        def func(x):
        	return x.split()[1:], x.split()[0]
        
        letters_logs.sort(key = func)
        '''
        
        return letters_logs + digit_logs

 

*Detail information of split() method 

https://www.w3schools.com/python/ref_string_split.asp

 

Python String split() Method

Python String split() Method ❮ String Methods Example Split a string into a list where each word is a list item: txt = "welcome to the jungle" x = txt.split() print(x) Try it Yourself » Definition and Usage The split() method splits a string into a list

www.w3schools.com

 

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

 

'LeetCode > Problems' 카테고리의 다른 글

LeetCode 49. Group Anagrams  (0) 2020.08.19
LeetCode 819. Most Common Word  (0) 2020.08.18
LeetCode 628. Maximum Product of Three Numbers  (0) 2020.07.09
LeetCode 91. Decode Ways  (0) 2020.06.21
LeetCode 226. Invert Binary Tree  (0) 2020.06.20

댓글