LeetCode 937 Reorder Log Files 解题报告
Posted yao1996
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 937 Reorder Log Files 解题报告相关的知识,希望对你有一定的参考价值。
题目要求
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.
题目分析及思路
给定一组字符串,每个字符串中的内容由空格隔开,且每个字符串开头是一个由数字和字母组成的标识符。之后要么全是数字(digit-logs),要么全是小写单词(letter-logs)。且保证标识符后一定会有内容。最后要求返回的结果是:letter-logs要在digit-logs前面,其中letter-logs要按字母表顺序排列(忽略标识符),digit-logs按原始顺序排列。可以遍历该数组,将标识符和后面的内容分开,将digit-logs按顺序放在单独的数组中,再对letter-logs进行排序。最后将两个列表组合。
python代码
class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
final_logs = []
digit_logs = []
digits = [‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘]
for log in logs:
idx = log.index(‘ ‘)
if log[idx+1] in digits:
digit_logs.append(log)
else:
final_logs.append(log)
final_logs.sort(key = lambda l:l[l.index(‘ ‘)+1:])
final_logs.extend(digit_logs)
return final_logs
以上是关于LeetCode 937 Reorder Log Files 解题报告的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 937. Reorder Data in Log Files
[LeetCode] 937. Reorder Data in Log Files
[Leetcode]937. Reorder Log Files给日志文件排序
LeetCode --- 937. Reorder Data in Log Files 解题报告