给定只含 “I”(增大)或 “D”(减小)的字符串 S ,令 N = S.length。
返回 [0, 1, …, N] 的任意排列 A 使得对于所有 i = 0, …, N-1,都有:
如果 S[i] == “I”,那么 A[i] < A[i+1]
如果 S[i] == “D”,那么 A[i] > A[i+1]
示例 1:
输出:“IDID”
输出:[0,4,1,3,2]
示例 2:
输出:“III”
输出:[0,1,2,3]
示例 3:
输出:“DDI”
输出:[3,2,0,1]
提示:
1 <= S.length <= 1000
S 只包含字符 “I” 或 “D”。
// 递归
func diStringMatch(S string) []int {
if S == "I" {
return []int{0, 1}
}
if S == "D" {
return []int{1, 0}
}
dsm := diStringMatch(S[:len(S)-1])
lastWord := S[len(S)-1]
if lastWord == 'I' {
return append(dsm, len(S))
} else {
dsm = append(dsm, len(S))
for i := len(S) - 1; i >= 0; i-- {
if S[i] == 'I' && dsm[i] > dsm[i+1] {
dsm[i], dsm[i+1] = dsm[i+1], dsm[i]
}
if S[i] == 'D' && dsm[i] < dsm[i+1] {
dsm[i], dsm[i+1] = dsm[i+1], dsm[i]
}
}
return dsm
}
}
func diStringMatch(S string) []int {
left := 0
right := len(S)
res := make([]int, 0)
for _, v := range S {
if v == 'I' {
res = append(res, left)
left++
} else {
res = append(res, right)
right--
}
}
res = append(res, left)
return res
}