题目
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]
总结
当s = 'I'
时,总选剩余的数中最小的数,当s='D'
时总选剩余的数中最大的数。这样相当于每次取符合条件的临界情况的一个贪心算法。具体实现如下:
class Solution:
def diStringMatch(self, S):
"""
:type S: str
:rtype: List[int]
"""
nums = [i for i in range(len(S) + 1)]
r = []
for s in S:
if s == 'I':
r.append(nums.pop(0))
else:
r.append(nums.pop(-1))
r.append(nums[0])
return r
但是仔细分析发现其实只需要用两个变量就可以记录住最小的值(从0开始每次遇到‘I’加一)和最大的值(从N开始每次遇到‘D’减一)
优化后代码:
class Solution:
def diStringMatch(self, S):
"""
:type S: str
:rtype: List[int]
"""
low = 0
high = len(S)
r = []
for s in S:
if s == 'I':
r.append(low)
low += 1
else:
r.append(high)
high -= 1
r.append(low)
return r