LeetCode 题解工作台

有效数字

给定一个字符串 s ,返回 s 是否是一个 有效数字 。 例如,下面的都是有效数字: "2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789" ,而接下…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

困难 · String-driven solution strategy

bolt

答案摘要

首先,我们判断字符串是否以正负号开头,如果是,将指针 向后移动一位。如果此时指针 已经到达字符串末尾,说明字符串只有一个正负号,返回 `false`。 如果当前指针 指向的字符是小数点,并且小数点后面没有数字,或者小数点后是一个 `e` 或 `E`,返回 `false`。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个字符串 s ,返回 s 是否是一个 有效数字

例如,下面的都是有效数字:"2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789",而接下来的不是:"abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"

一般的,一个 有效数字 可以用以下的规则之一定义:

  1. 一个 整数 后面跟着一个 可选指数
  2. 一个 十进制数 后面跟着一个 可选指数

一个 整数 定义为一个 可选符号 '-' 或 '+' 后面跟着 数字

一个 十进制数 定义为一个 可选符号 '-' 或 '+' 后面跟着下述规则:

  1. 数字 后跟着一个 小数点 .
  2. 数字 后跟着一个 小数点 . 再跟着 数位
  3. 一个 小数点 . 后跟着 数位

指数 定义为指数符号 'e''E',后面跟着一个 整数

数字 定义为一个或多个数位。

 

示例 1:

输入:s = "0"

输出:true

示例 2:

输入:s = "e"

输出:false

示例 3:

输入:s = "."

输出:false

 

提示:

  • 1 <= s.length <= 20
  • s 仅含英文字母(大写和小写),数字(0-9),加号 '+' ,减号 '-' ,或者点 '.'
lightbulb

解题思路

方法一:分情况讨论

首先,我们判断字符串是否以正负号开头,如果是,将指针 ii 向后移动一位。如果此时指针 ii 已经到达字符串末尾,说明字符串只有一个正负号,返回 false

如果当前指针 ii 指向的字符是小数点,并且小数点后面没有数字,或者小数点后是一个 eE,返回 false

接着,我们用两个变量 dotdotee 分别记录小数点和 eE 的个数。

用指针 jj 指向当前字符:

  • 如果当前字符是小数点,并且此前出现过小数点或者 eE,返回 false。否则,我们将 dotdot 加一;
  • 如果当前字符是 eE,并且此前出现过 eE,或者当前字符是开头或结尾,返回 false。否则,我们将 ee 加一;然后判断下一个字符是否是正负号,如果是,将指针 jj 向后移动一位。如果此时指针 jj 已经到达字符串末尾,返回 false
  • 如果当前字符不是数字,返回 false

遍历完字符串后,返回 true

时间复杂度 O(n)O(n),其中 nn 为字符串长度。空间复杂度 O(1)O(1)

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
29
30
class Solution:
    def isNumber(self, s: str) -> bool:
        n = len(s)
        i = 0
        if s[i] in '+-':
            i += 1
        if i == n:
            return False
        if s[i] == '.' and (i + 1 == n or s[i + 1] in 'eE'):
            return False
        dot = e = 0
        j = i
        while j < n:
            if s[j] == '.':
                if e or dot:
                    return False
                dot += 1
            elif s[j] in 'eE':
                if e or j == i or j == n - 1:
                    return False
                e += 1
                if s[j + 1] in '+-':
                    j += 1
                    if j == n - 1:
                        return False
            elif not s[j].isnumeric():
                return False
            j += 1
        return True
speed

复杂度分析

指标
时间complexity depends on scanning each character once, making it O(n) where n is the length of the string. Space complexity is O(1) since only a few flags are maintained, independent of input size.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check for correct handling of leading and trailing spaces, plus/minus signs, and dots.

  • question_mark

    Expect edge cases where 'e' is present without proper numeric bases or exponents.

  • question_mark

    Watch for multiple dots or misplaced signs that violate the valid number format.

warning

常见陷阱

外企场景
  • error

    Assuming any digit sequence is valid without validating decimal and exponent placement.

  • error

    Failing to reject strings with multiple signs or multiple dots.

  • error

    Overlooking cases where the exponent part is missing digits or improperly formatted.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Validate numbers allowing only integers, disallowing decimal points and exponents.

  • arrow_right_alt

    Check for scientific notation exclusively with 'E' or 'e' but reject plain decimals.

  • arrow_right_alt

    Allow whitespace trimming at the beginning and end while maintaining numeric validation rules.

help

常见问题

外企场景

有效数字题解:String-driven solution … | LeetCode #65 困难