LeetCode 题解工作台
数组中字符串的最大值
一个由字母和数字组成的字符串的 值 定义如下: 如果字符串 只 包含数字,那么值为该字符串在 10 进制下的所表示的数字。 否则,值为字符串的 长度 。 给你一个字符串数组 strs ,每个字符串都只由字母和数字组成,请你返回 strs 中字符串的 最大值 。 示例 1: 输入: strs = ["…
2
题型
8
代码语言
3
相关题
当前训练重点
简单 · 数组·string
答案摘要
我们定义一个函数 ,用于计算字符串 的值。如果 只包含数字,那么 就是 在十进制下的值;否则 就是 的长度。 答案为 $\max\limits_{s \in \textit{strs}} f(s)$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
一个由字母和数字组成的字符串的 值 定义如下:
- 如果字符串 只 包含数字,那么值为该字符串在
10进制下的所表示的数字。 - 否则,值为字符串的 长度 。
给你一个字符串数组 strs ,每个字符串都只由字母和数字组成,请你返回 strs 中字符串的 最大值 。
示例 1:
输入:strs = ["alic3","bob","3","4","00000"] 输出:5 解释: - "alic3" 包含字母和数字,所以值为长度 5 。 - "bob" 只包含字母,所以值为长度 3 。 - "3" 只包含数字,所以值为 3 。 - "4" 只包含数字,所以值为 4 。 - "00000" 只包含数字,所以值为 0 。 所以最大的值为 5 ,是字符串 "alic3" 的值。
示例 2:
输入:strs = ["1","01","001","0001"] 输出:1 解释: 数组中所有字符串的值都是 1 ,所以我们返回 1 。
提示:
1 <= strs.length <= 1001 <= strs[i].length <= 9strs[i]只包含小写英文字母和数字。
解题思路
方法一:模拟
我们定义一个函数 ,用于计算字符串 的值。如果 只包含数字,那么 就是 在十进制下的值;否则 就是 的长度。
答案为 。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n), where n is the number of strings in the array, and space complexity is O(1) since only a few variables are used to track the maximum value during iteration. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Tests understanding of string manipulation and number conversion.
- question_mark
Checks if the candidate can correctly handle different data types (strings and integers).
- question_mark
Assesses problem-solving skills in array traversal and maximum value tracking.
常见陷阱
外企场景- error
Failing to convert digit-only strings into integers, leading to incorrect comparisons.
- error
Not properly handling strings that consist solely of letters (should rely on length).
- error
Confusing the value of strings that contain both letters and digits, which requires taking their length.
进阶变体
外企场景- arrow_right_alt
Consider additional edge cases with strings of varying lengths and characters.
- arrow_right_alt
Handle cases where multiple strings have the same value, ensuring the correct maximum is returned.
- arrow_right_alt
Explore performance optimizations when dealing with large input sizes, such as avoiding redundant calculations.