Skip to content

53 表示数值的字符串

题目描述

请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。但"12e","1a3.14","1.2.3","+-5"和"12e+5.4"都不是。

解题思路

核心思想:按照数值的格式规则逐个字符检查。

关键步骤

  1. 可选的正负号
  2. 整数部分(可选)
  3. 小数部分(可选)
  4. 指数部分(可选)

时间复杂度:O(n) 空间复杂度:O(1)

Python 实现

python
def is_numeric(s):
    """
    判断字符串是否表示数值

    Args:
        s: 字符串

    Returns:
        bool: 是否是数值
    """
    if not s:
        return False

    # 去除首尾空格
    s = s.strip()
    if not s:
        return False

    index = 0
    has_dot = False
    has_exp = False

    # 检查符号
    if s[index] in ['+', '-']:
        index += 1

    # 检查整数部分
    while index < len(s) and s[index].isdigit():
        index += 1

    # 检查小数部分
    if index < len(s) and s[index] == '.':
        has_dot = True
        index += 1
        while index < len(s) and s[index].isdigit():
            index += 1

    # 检查指数部分
    if index < len(s) and (s[index] == 'e' or s[index] == 'E'):
        has_exp = True
        index += 1
        # 检查指数的符号
        if index < len(s) and s[index] in ['+', '-']:
            index += 1
        # 检查指数的数字
        if index >= len(s) or not s[index].isdigit():
            return False
        while index < len(s) and s[index].isdigit():
            index += 1

    return index == len(s)


# 测试代码
if __name__ == "__main__":
    test_cases = [
        "+100",
        "5e2",
        "-123",
        "3.1416",
        "-1E-16",
        "12e",
        "1a3.14",
        "1.2.3",
        "+-5",
        "12e+5.4",
        ".",
        "0.5",
    ]

    for s in test_cases:
        print(f"'{s}' {'是' if is_numeric(s) else '不是'}数值")

# 输出:
# '+100' 是数值
# '5e2' 是数值
# '-123' 是数值
# '3.1416' 是数值
# '-1E-16' 是数值
# '12e' 不是数值
# '1a3.14' 不是数值
# '1.2.3' 不是数值
# '+-5' 不是数值
# '12e+5.4' 不是数值
# '.' 不是数值
# '0.5' 是数值
最近更新

基于 MIT 许可发布