LeetCode/Problems

LeetCode 937. Reorder Data in Log Files

벤진[Benzene] 2020. 8. 17. 11:32

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]