You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

字符串有效数字验证:代码遇Time Limit Exceeded错误求解决

解决有效数字检查的超时问题

首先先明确你的需求:

  • 有效数字示例:1234、-1234、12.4、0.6、-0.6、-1234567890.123456789
  • 无效数字示例:+123、123.、.6、00.6、12-.6335
  • 核心规则:首字符是0时必须紧跟小数点

为什么会出现Time Limit Exceeded?

从你贴出的代码片段来看,里面有while number_string[0] == "-"这样的逻辑,但你没有在循环内修改number_string的值!比如如果输入的字符串是"---123",这个循环会一直判断第一个字符是-,永远跳不出来,直接进入死循环,自然就触发超时了。这是最可能的问题根源。

修正后的实现方案

我们可以用逐字符线性遍历的方式,避免死循环,同时严格遵循所有规则:

def valid_float(number_string):
    # 空字符串直接判定无效
    if not number_string:
        return False
    
    # 标记是否已出现小数点、是否有有效数字
    has_decimal = False
    has_digit = False
    str_length = len(number_string)
    
    for idx, char in enumerate(number_string):
        # 处理负号:只能出现在第一个位置
        if char == "-":
            if idx != 0:
                return False
            continue
        
        # 处理小数点:只能出现一次,且不能在首尾位置
        if char == ".":
            if has_decimal:
                return False
            if idx == 0 or idx == str_length - 1:
                return False
            # 检查首0规则:如果第一个字符是0,必须紧跟小数点
            if idx == 1 and number_string[0] == "0":
                pass
            elif idx > 1 and number_string[0] == "0" and number_string[1] != ".":
                return False
            has_decimal = True
            continue
        
        # 处理数字字符
        if char.isdigit():
            has_digit = True
            # 检查首0规则:首字符是0且后面不是小数点,直接无效(比如0123)
            if idx == 0 and char == "0" and str_length > 1 and number_string[1] != ".":
                return False
            continue
        
        # 出现非数字、非负号、非小数点的字符,直接无效
        return False
    
    # 必须至少包含一个有效数字
    return has_digit

测试验证

用你的示例测试一下:

  • 有效输入:valid_float("0.6") → True;valid_float("-1234.56") → True
  • 无效输入:valid_float("+123") → False;valid_float("00.6") → False;valid_float("12-.6335") → False

这个实现是线性遍历,时间复杂度为O(n),不会出现死循环,完全能避免超时问题。

内容的提问来源于stack exchange,提问作者qwert123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:29:03