LeetCode in Kotlin

2496. Maximum Value of a String in an Array

Easy

The value of an alphanumeric string can be defined as:

Given an array strs of alphanumeric strings, return the maximum value of any string in strs.

Example 1:

Input: strs = [“alic3”,”bob”,”3”,”4”,”00000”]

Output: 5

Explanation:

Hence, the maximum value is 5, of “alic3”.

Example 2:

Input: strs = [“1”,”01”,”001”,”0001”]

Output: 1

Explanation: Each string in the array has value 1. Hence, we return 1.

Constraints:

Solution

class Solution {
    fun maximumValue(strs: Array<String>): Int {
        var maxVal = 0
        for (s in strs) {
            maxVal = Math.max(maxVal, value(s))
        }
        return maxVal
    }

    private fun value(s: String): Int {
        var total = 0
        for (ch in s.toCharArray()) {
            total = if (ch in '0'..'9') {
                total * 10 + (ch.code - '0'.code)
            } else {
                return s.length
            }
        }
        return total
    }
}