难度: Easy
原题连接
内容描述
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: ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]
Note:
0 <= logs.length <= 100
3 <= logs[i].length <= 100
logs[i] is guaranteed to have an identifier, and a word after the identifier.
思路 1 - 时间复杂度: O(N^2)- 空间复杂度: O(1)******
sb题没什么好说的
就稍微注意一下下面的例子就懂了
Input:
["j mo", "5 m w", "g 07", "o 2 0", "t q h"]
Output:
["j mo","5 m w","t q h","g 07","o 2 0"]
Expected:
["5 m w","j mo","t q h","g 07","o 2 0"]
beats 100%
class Solution:
def reorderLogFiles(self, logs):
"""
:type logs: List[str]
:rtype: List[str]
"""
digits_log_idx = []
letter_log = {}
letter_logs = []
def allDigit(word):
return all(w.isdigit() for w in word)
for idx, log in enumerate(logs):
if allDigit(log.split(' ')[-1]):
digits_log_idx.append(idx)
else:
letters = tuple(log.split(' ')[1:]) # identifier后面的所有letters
letter_log[letters] = idx
letter_logs.append(letters)
letter_logs.sort()
res = []
for log in letter_logs:
res.append(logs[letter_log[log]])
for idx in digits_log_idx:
res.append(logs[idx])
return res