gpt4 book ai didi

937. Reorder Data in Log Files 重新排列日志文件

转载 作者:大佬之路 更新时间:2024-01-31 14:16:20 25 4
gpt4 key购买 nike

键词:力扣,LeetCode,算法,题解,答案,937,重新排列,日志文件,Python

题目地址:https://leetcode.com/problems/max-points-on-a-line/description/

题目描述

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

Foreach 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.

Wewill 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:

1、 0<=logs.length<=100
2、 3<=logs[i].length<=100
3、 logs[i]isguaranteedtohaveanidentifier,andawordaftertheidentifier.;

题目大意

要求我们按照特定的格式重新排序日志

日志 的格式是第一个单词是 日志标识符,后面的都是 日志内容。 有两种 日志,一种内容是纯数字的(数字日志),一种内容纯英文字符的(字母日志)。

 

要求的排序规则:

  • 把所有的英文 日志 放到数字 日志 前面。
  • 而且如果是字母日志,需要按照内容日志 进行排序,当内容相同的时候按照标识符排序;
  • 如果是数字 日志,保持原来的顺序。

 

解题方法

拆分和排序

看起来题目很长,但是只要是字符串处理题,对于 python 都很简单。

我用了两个列表,分别存储字母日志数字日志,先分别排序,再拼接到一起。

1、 首先需要进行分割成标识符内容
2、内容的第一个单词进行判断:

  • 如果是英文字符串,说明是字母日志,那么把内容标识符构成 元组 放到 letters 的列表里;
  • 如果是数字字符串,说明是数字日志,那么直接把当前的这个日志放到 nums 列表里。 3、 然后我们需要对letters进行排序:因为元组里首先是内容,然后是标识符,所以sort()会先对内容进行排序,然后再对标识符进行排序;
    4、letters排序的结果中提取出所有的内容,并与nums拼接在一起,返回即可;
class Solution(object):
    def reorderLogFiles(self, logs):
        """
        :type logs: List[str]
        :rtype: List[str]
        """
        letters = []
        nums = []
        for log in logs:
            logsplit = log.split(" ")
            if logsplit[1].isalpha():
                letters.append((" ".join(logsplit[1:]), logsplit[0]))
            else:
                nums.append(log)
        letters.sort()
        return [letter[1] + " " + letter[0] for letter in letters] + nums

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

复杂度

  • 时间复杂度:O(N∗log(N))
  • 空间复杂度:O(N)

总结

1、 对于Easy的题目,根本不用多想,怎么方便怎么来,基本都能过;

DDKK.COM 弟弟快看-教程,程序员编程资料站,版权归原作者所有

本文经作者:负雪明烛 授权发布,任何组织或个人未经作者授权不得转发

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com