题解 | #表达式求值#

表达式求值

https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4

object Solution {
    fun solve(s: String): Int {
        var inputStr = s
        // recurve parentheses
        while (inputStr.contains('(')) {
            val startIdx = inputStr.lastIndexOf('(')
            val tempSubStr = inputStr.substring(startIdx.plus(1))
            val endIdx = tempSubStr.indexOf(')')
            val subStr = tempSubStr.substring(0, endIdx)
            val startStr = inputStr.substring(0, startIdx)
            val startStrLength = startStr.length
            val endStr = inputStr.substring(endIdx.plus(startStrLength).plus(2))
            val solve = solve(subStr)
            inputStr = startStr.plus(solve).plus(endStr)
            if (inputStr.contains("*-")) {
                val flagIdx = inputStr.indexOf("*-")
                var numbStr = ""
                val arrayOf = arrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*')
                for (i in flagIdx - 1 downTo 0) {
                    if (inputStr[i] in arrayOf) {
                        numbStr = inputStr[i].plus(numbStr)
                    } else {
                        break
                    }
                }
                inputStr = inputStr.replace("*-", "*")
                inputStr = inputStr.substring(0, flagIdx.minus(numbStr.length))
                        .plus("-")
                        .plus(numbStr)
                        .plus(inputStr.substring(flagIdx))
            }
            if (inputStr.contains("--")) {
                inputStr = inputStr.replace("--", "+")
            }
            if (inputStr.contains("+-")) {
                inputStr = inputStr.replace("+-", "-")
            }
        }
        // without parentheses
        val tempStack = mutableListOf<Int>()
        var tempNumber = ""
        var prevOperator = '+'
        for ((index, c) in inputStr.withIndex()) {
            if (c in '0'..'9') {
                tempNumber = tempNumber.plus(c)
                if (index != inputStr.lastIndex) {
                    continue
                }
            }
            if (c == '-' && index == 0) {
                tempNumber = "-"
            } else {
                val tempInt = tempNumber.toInt()
                tempStack.add(when (prevOperator) {
                    '+' -> tempInt
                    '-' -> -tempInt
                    '*' -> tempStack.removeLast() * tempInt
                    else -> tempInt
                })
                tempNumber = ""
                prevOperator = c
            }
        }
        return tempStack.reduce { acc, i -> acc.plus(i) }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务