Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/2496.html
2496. Maximum Value of a String in an Array
- Difficulty: Easy.
- Related Topics: .
- Similar Questions: Maximum Subarray.
Problem
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.
Solution (Java, C++, Python)
-
class Solution { public int maximumValue(String[] strs) { int ans = 0; for (String s : strs) { ans = Math.max(ans, f(s)); } return ans; } private int f(String s) { for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) >= 'a' && s.charAt(i) <= 'z') { return s.length(); } } return Integer.parseInt(s); } }
-
class Solution { public: int maximumValue(vector<string>& strs) { auto f = [](string& s) { int n = s.size(), m = 0; for (char& c : s) { if (!isdigit(c)) return n; m = m * 10 + (c - '0'); } return m; }; int ans = 0; for (auto& s : strs) ans = max(ans, f(s)); return ans; } };
-
class Solution: def maximumValue(self, strs: List[str]) -> int: def f(s): return int(s) if all(c.isdigit() for c in s) else len(s) return max(f(s) for s in strs)
-
func maximumValue(strs []string) (ans int) { f := func(s string) int { n, m := len(s), 0 for _, c := range s { if c >= 'a' && c <= 'z' { return n } m = m*10 + int(c-'0') } return m } for _, s := range strs { if t := f(s); ans < t { ans = t } } return }
-
function maximumValue(strs: string[]): number { let ans = 0; for (const s of strs) { const num = Number(s); ans = Math.max(ans, Number.isNaN(num) ? s.length : num); } return ans; }
-
impl Solution { pub fn maximum_value(strs: Vec<String>) -> i32 { let mut ans = 0; for s in strs.iter() { let num = s.parse().unwrap_or(s.len()); ans = ans.max(num); } ans as i32 } }
-
public class Solution { public int MaximumValue(string[] strs) { return strs.Max(f); } private int f(string s) { int x = 0; foreach (var c in s) { if (c >= 'a') { return s.Length; } x = x * 10 + (c - '0'); } return x; } }
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).