LeetCode: Find Permutation

172 阅读1分钟

题目

By now, you are given a secret signature consisting of character 'D' and 'I'. 'D' represents a decreasing relationship between two numbers, 'I' represents an increasing relationship between two numbers. And our secret signature was constructed by a special integer array, which contains uniquely all the different number from 1 to n (n is the length of the secret signature plus 1). For example, the secret signature "DI" can be constructed by array [2,1,3] or [3,1,2], but won't be constructed by array [3,2,4] or [2,1,3,4], which are both illegal constructing special string that can't represent the "DI" secret signature.

On the other hand, now your job is to find the lexicographically smallest permutation of [1, 2, ... n] could refer to the given secret signature in the input.

解法

  1. 一开始我想到的是用backtracking的方法,当找到一个复合条件的解之后就暂停,但是这样超时了,所以肯定有更有解法
  2. 看了别人的解答后发现,用一种O(n)的方法可以得到正确答案
  • 因为结果是1..n 的一种排列,所以先写出一个1..n的序列。当是连续的“I”时,序列不需要改变,但当是连续的“D”时,需要直接reverse部分序列,如果从i到j都是D,那么需要reverse[i-1,j]
class Solution:
    def findPermutation(self, s: str) -> List[int]:
        N = len(s)+1
        result = list(range(1,N+1))
        start = -1
        prevD = False
        for i in range(N-1):
            if s[i] == 'D':
                prevD = True
                if start == -1:
                    start = i
            else:
                if prevD:
                    self.reverse(result, start, i)
                    start = -1
                prevD = False
        if prevD:
            self.reverse(result, start, N-1)
        return result
    def reverse(self, result, i, j):
        while i < j:
            temp = result[i]
            result[i] = result[j]
            result[j] = temp
            i+=1
            j-=1