2023年10月21日 星期六

10/20 每日一題 (根據DI String 放入配對的數組, 遇到遞增時放入最小, 反之最大)

A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:

  • s[i] == 'I' if perm[i] < perm[i + 1], and
  • s[i] == 'D' if perm[i] > perm[i + 1].

Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.

 

Example 1:

Input: s = "IDID"
Output: [0,4,1,3,2]

Example 2:

Input: s = "III"
Output: [0,1,2,3]

Example 3:

Input: s = "DDI"
Output: [3,2,0,1]

 

Constraints:

  • 1 <= s.length <= 105
  • s[i] is either 'I' or 'D'.

 class Solution:

   
    def diStringMatch(self, s: str) -> List[int]:
        #遇到I 就給最小, 反之給最大
        perm = [i for i in range(len(s)+1)]
        res=[]
        for i in s:
            if i == 'I':
                #因為下個是遞增, 所以放入最小
                res.append(perm.pop(0))
            else:
                res.append(perm.pop())
        '加入最後一項'
        res.append(perm.pop())
        print(f'res={res}')
        return res

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


標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁