leetpycode/easy/summary_ranges.py

33 lines
1.1 KiB
Python

# https://leetcode.com/problems/summary-ranges
from typing import List
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
curr_num: List[int] = []
result: List[str] = []
for num in nums:
if len(curr_num) == 0:
curr_num.append(num)
continue
match len(curr_num):
case 0:
curr_num.append(num)
case 1:
if curr_num[0] + 1 == num:
curr_num.append(num)
else:
result.append(str(curr_num[0]))
curr_num = [num]
case 2:
if curr_num[1] + 1 == num:
curr_num[1] += 1
else:
result.append('->'.join([str(curr_num[0]), str(curr_num[1])]))
curr_num = [num]
if len(curr_num) == 1:
result.append(str(curr_num[0]))
elif len(curr_num) == 2:
result.append('->'.join([str(curr_num[0]), str(curr_num[1])]))
return result