LeetCode 2496. Maximum Value of a String in an Array Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
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 <= 100
  • 1 <= strs[i].length <= 9
  • strs[i] consists of only lowercase English letters and digits.

Solutions

Solution 1

PythonJavaC++GoTypeScriptRustC#C
class Solution: def maximumValue(self, strs: List[str]) -> int: def f(s: str) -> int: return int(s) if all(c.isdigit() for c in s) else len(s) return max(f(s) for s in strs)(code-box)

Solution 2

PythonRust
class Solution: def maximumValue(self, strs: List[str]) -> int: def f(s: str) -> int: x = 0 for c in s: if c.isalpha(): return len(s) x = x * 10 + ord(c) - ord("0") return x return max(f(s) for s in strs)(code-box)

Solution 3

Rust
use std::cmp::max; impl Solution { pub fn maximum_value(strs: Vec<String>) -> i32 { let mut ans = 0; for s in strs { match s.parse::<i32>() { Ok(v) => { ans = max(ans, v); } Err(_) => { ans = max(ans, s.len() as i32); } } } ans } }(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !