1. 程式人生 > >942. DI String Match 越界錯誤因為空表,索引0不存在

942. DI String Match 越界錯誤因為空表,索引0不存在

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", then A[i] < A[i+1]
  • If S[i] == "D"
    , then A[i] > A[i+1]

 

Example 1:

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

Example 2:

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

Example 3:

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

 

Note:

  1. 1 <= S.length <= 10000
  2. S only contains characters "I" or "D".

 

下面的是錯的:

class Solution:
    def diStringMatch(self, S):
        """
        :type S: str
        :rtype: List[int]
        """
        N=len(S)
        A=[]
        for i in range(N):
            A.append(i)
            
        for i in range(N):
            if S[i] == "I":
                if A[i]>A[i+1]:
                    A[i],A[i+1]=A[i+1],A[i]
            if S[i] == "D":
                if A[i]<A[i+1]:
                    A[i],A[i+1]=A[i+1],A[i]
        return A
        

Your input

"IDID"

Output

[0,2,1,4,3]

Diff

Expected

[0,4,1,3,2]

下面的是正確的:

思路是我們把0放在第一個位置。如果S[1]是I,則我們把最大的N,放在A[1]上,如此。

class Solution:
    def diStringMatch(self, S):
        """
        :type S: str
        :rtype: List[int]
        """
        N=len(S)
        A=[]
        countH=countL=0
     #   for i in range(N+1):
     #       A.append(i)
            
        for i in range(N):
            if S[i] == "I":
                countL=countL+1
                A[i]=countL-1
            if S[i] == "D":
                countH=countH+1
                A[i]=N-countH+1
                    
        return A
        

 

第A[i]=countL-1行報錯:

Line 16: IndexError: list assignment index out of range

因為A是空的列表,索引0不存在,比如:

>>> a=[]
>>> a[0]="a"
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    a[0]="a"
IndexError: list assignment index out of range
>>> a.append("a")
>>> print(a)
['a']

改:

class Solution:
    def diStringMatch(self, S):
        """
        :type S: str
        :rtype: List[int]
        """
        N=len(S)
        A=[]
        countH=countL=0
        for i in range(N+1):
            A.append(None)
            
        for i in range(N):
            if S[i] == "I":
                countL=countL+1
                A[i]=countL-1
            if S[i] == "D":
                countH=countH+1
                A[i]=N-countH+1 
        A[N]=N-countH
                    
        return A