題目:
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"
, thenA[i] < A[i+1]
- If
S[i] == "D"
, thenA[i] > A[i+1]
範例:
Input: "IDID"Output: [0,4,1,3,2]
這裡要注意一下
Golang的字串存的是位元組
所以在for中取出要比較的話
要轉換一下型態
或是直接比較ASCII code也是可以
詳細可以看一下 這裡
解法:
func diStringMatch(S string) []int { max := len(S) min := 0 result := make([]int, max) for index, value := range S { if value == 73 { result[index] = min min++ } else { result[index] = max max-- } } result = append(result, min) return result}
沒有留言:
張貼留言