2496. Maximum Value of a String in an Array
Description
The value of an alphanumeric string can be defined as:
- The numeric representation of the string in base
10, if it comprises of digits only. - The length of the string, otherwise.
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: - "alic3" consists of both letters and digits, so its value is its length, i.e. 5. - "bob" consists only of letters, so its value is also its length, i.e. 3. - "3" consists only of digits, so its value is its numeric equivalent, i.e. 3. - "4" also consists only of digits, so its value is 4. - "00000" consists only of digits, so its value is 0. 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:
1 <= strs.length <= 1001 <= strs[i].length <= 9strs[i]consists of only lowercase English letters and digits.
Solutions
Solution 1
Thinking
A string is either its decimal value or, if it contains a letter, its length. Lengths are at most \(9\). Test \(\textit{isdigit}\) then take \(\textit{int}\) or \(\textit{len}\), and keep the maximum.
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 | |
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
Solution 2
Thinking
Method 1 parses the whole string after an all-digit check. Accumulating digit by digit returns the length on the first letter and otherwise builds the integer, without a separate scan.
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
Solution 3
Thinking
Same rule as method 1 via a built-in parse: on success use the number, on failure use the length. The error path is exactly “contains a non-digit”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |