942. DI String Match 越界错误因为空表,索引0不存在

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mygodhome/article/details/84980020

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

猜你喜欢

转载自blog.csdn.net/mygodhome/article/details/84980020