LeetCode 942 DI String Match 解題報告
題目要求
Given a string S
that only contains "I" (increase) or "D" (decrease), let N = S.length
.
Return any permutation A
of [0, 1, ..., N]
such that for all i = 0, ..., N-1
:
- If
S[i] == "I",
thenA[i] < A[i+1]
- If
S[i] == "D",
thenA[i] > A[i+1]
題目分析及思路
題目給出一個只包含I或D的字符串,要求返回一個序列,序列長度為字符串長度N+1。當字母為I,則序列的對應位置比後面位置的值要大;若字母為D,則相反。我們可以使第一個出現I的位置對應的是0,第一個D出現的位置對應的是N,那麽無論這個位置後面出現的是另外的哪個數字,當前的位置都能滿足題設條件。我們每次遇見I都比之前的I增加1,每次遇到D都比之前的D減小1。這樣會盡可能的給後面的數字讓出空間。
python代碼?
class Solution:
def diStringMatch(self, S):
"""
:type S: str
:rtype: List[int]
"""
N = len(S)
min,max = 0,N
res = list()
for s in S:
if s == ‘I‘:
res.append(min)
min = min + 1
if s == ‘D‘:
res.append(max)
max = max - 1
res.append(min)
return res
LeetCode 942 DI String Match 解題報告