【LeetCode】937. Reorder Log Files 解題報告(Python)
作者: 負雪明燭
id: fuxuemingzhu
個人部落格: http://fuxuemingzhu.cn/
目錄
題目地址:https://leetcode.com/problems/max-points-on-a-line/description/
題目描述
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.
題目大意
Log的格式是第一個單詞是Log的索引,後面的都是Log的內容。有兩種Log,一種內容是純數字的,一種內容是純英文字元的。現在要求,把所有的英文Log放到數字Log前面。而且如果是純英文的字元Log,需要按照內容對Log進行排序,當內容相同的時候按照索引排序;如果是數字Log,保持原來的順序。
解題方法
分割和排序
周賽第一題,看起來題目很長,但是隻要是字串處理題,對於python都很簡單。首先需要進行分割成索引和內容,然後對內容的第一個單詞進行判斷,如果是英文字串,那麼把內容和索引構成tuple放到letters的列表裡;如果是數字字串,那麼直接把當前的這個log放到nums列表裡。
然後我們需要對letters進行排序,因為tuple裡首先是內容,然後是索引,所以會先對內容進行排序,然後再對索引進行排序。
把letters排序的結果重置成正常的狀態和nums拼接在一起,返回即可。
時間複雜度是O(NlogN),空間複雜度是O(N)。
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
日期
2018 年 11 月 11 日 —— 剁手節快樂