942. 增减字符串匹配

 

给定只含 "I"(增大)或 "D"(减小)的字符串 S ,令 N = S.length

返回 [0, 1, ..., N] 的任意排列 A 使得对于所有 i = 0, ..., N-1,都有:

  • 如果 S[i] == "I",那么 A[i] < A[i+1]
  • 如果 S[i] == "D",那么 A[i] > A[i+1]

 

示例 1:

输入:"IDID"
输出:[0,4,1,3,2]

示例 2:

输入:"III"
输出:[0,1,2,3]

示例 3:

输入:"DDI"
输出:[3,2,0,1]

 

提示:

  • 1 <= S.length <= 10000
  • S 只包含字符 "I" 或 "D"

对符合条件的pick[]中选最大值 or 最小值

class Solution:
    def diStringMatch(self, S: str) -> List[int]:
        n=len(S)
        pick=[i for i in range(n+1)]
        if S[0]=='I':
            res=[0]
            pick.pop(0)
            if n==1:return [0,1]  
        else:
            res=[n]
            pick.pop(-1)
            if n==1:return [1,0]
        for i in range(1,n):
            if S[i-1]=='I':
                if S[i]=='I':res.append(pick.pop(0))
                else:res.append(pick.pop(-1))
            else:
                if S[i]=='D':res.append(pick.pop(-1))
                else:res.append(pick.pop(0))
        res.append(pick.pop())
        return res 

 

 提炼一下核心思维进一步优化:

class Solution:
    def diStringMatch(self, S: str) -> List[int]:
        l,r=0,len(S)
        res=[]
        for i in S:
            if i=='I':
                res.append(l)
                l+=1
            else:
                res.append(r)
                r-=1
        res.append(l)
        return res 

 

posted @ 2020-10-15 17:12  XXXSANS  阅读(136)  评论(0编辑  收藏  举报