LeetCode 题解工作台

数组中字符串的最大值

一个由字母和数字组成的字符串的 值 定义如下: 如果字符串 只 包含数字,那么值为该字符串在 10 进制下的所表示的数字。 否则,值为字符串的 长度 。 给你一个字符串数组 strs ,每个字符串都只由字母和数字组成,请你返回 strs 中字符串的 最大值 。 示例 1: 输入: strs = ["…

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·string

bolt

答案摘要

我们定义一个函数 ,用于计算字符串 的值。如果 只包含数字,那么 就是 在十进制下的值;否则 就是 的长度。 答案为 $\max\limits_{s \in \textit{strs}} f(s)$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

一个由字母和数字组成的字符串的  定义如下:

  • 如果字符串 包含数字,那么值为该字符串在 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 <= 100
  • 1 <= strs[i].length <= 9
  • strs[i] 只包含小写英文字母和数字。
lightbulb

解题思路

方法一:模拟

我们定义一个函数 f(s)f(s),用于计算字符串 ss 的值。如果 ss 只包含数字,那么 f(s)f(s) 就是 ss 在十进制下的值;否则 f(s)f(s) 就是 ss 的长度。

答案为 maxsstrsf(s)\max\limits_{s \in \textit{strs}} f(s)

时间复杂度 O(n)O(n),其中 nn 是数组 strsstrs 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
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)
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

数组中字符串的最大值题解:数组·string | LeetCode #2496 简单