Share my python codes, easy to understand


  • 0
    C

    After simple search, I did not find similar codes. just to share.

    Example:
    "DDIIDI"
    output: [3,2,1,4,6,5,7]
    1, at beginning: [1,2,3,4,5,6,7]
    2, reverse 1,2,3 (index: 0,1,2) because of the first D block (D's index:0,1)
    3, reverse 5,6 (index: 4,5) because of the second D block (D's index:4)

    Codes:

    class Solution(object):
        def findPermutation(self, s):
            """
            :type s: str
            :rtype: List[int]
            """
            L = len(s)
            if L==0:
                return [1]
                
            ind, l, record = -1, 0, []
            for i, c in enumerate(s):
                if c=='I':
                    if ind!=-1 and l>0:
                        record.append( [ind, l] )
                    ind, l = -1, 0
                    
                else:
                    if l==0:
                        ind, l = i, 1
                    else:
                        l += 1
                        
            if ind!=-1 and l>0:
                record.append( [ind, l] )
                
            #print record
            ans = range(1,L+2)
            def helper(lst, start, end):
                while start<end:
                    lst[start], lst[end] = lst[end], lst[start]
                    start += 1
                    end -= 1
                    
            for i, l in record:
                helper(ans, i, i+l)
                
            return ans
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.