LeetCode之DI String Match(Kotlin)

問題: 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:git

  • 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]
 

Note:

1 <= S.length <= 10000
S only contains characters "I" or "D".
複製代碼

方法: 若是是增長就是最小數,若是是減小就是最大數;最大數後就是次大數,最小數以後就是次小數。固然這只是全部狀況中的一種,也是最容易代碼化的。github

具體實現:bash

class DIStringMatch {
    fun diStringMatch(S: String): IntArray {
        var ins = S.length
        var des = 0
        val result = arrayOfNulls<Int>(S.length + 1)
        var index = 0
        for (ch in S) {
            if(ch == 'I') {
                result[index] = des
                des++
            } else {
                result[index] = ins
                ins--
            }
            index++
        }
        // result[index] = ins
        result[index] = des
        return result.requireNoNulls().toIntArray()
    }
}

fun main(args: Array<String>) {
    val input = "IIID"
    val diStringMatch = DIStringMatch()
    CommonUtils.printArray(diStringMatch.diStringMatch(input).toTypedArray())
}
複製代碼

有問題隨時溝通ui

具體代碼實現能夠參考Githubspa

相關文章
相關標籤/搜索