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

相关文章
相关标签/搜索