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:

  • 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".

方法:
如果是增加就是最小数,如果是减少就是最大数;最大数后就是次大数,最小数之后就是次小数。当然这只是所有情况中的一种,也是最容易代码化的。

具体实现:

class DIStringMatch {
    fun diStringMatch(S: String): IntArray {
        var ins = S.length
        var des = 0
        val result = arrayOfNulls(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) {
    val input = "IIID"
    val diStringMatch = DIStringMatch()
    CommonUtils.printArray(diStringMatch.diStringMatch(input).toTypedArray())
}

有问题随时沟通

具体代码实现可以参考Github

你可能感兴趣的:(LeetCode之DI String Match(Kotlin))