LeetCode 65. 有效数字

题目描述

65. 有效数字

思路分析

解法一:一次遍历状态判断(推荐)

核心思路

  • 扫描字符串,记录是否出现过数字、小数点、指数符号。
  • 小数点只能出现一次且不能在指数之后;指数只能出现一次且前面必须有数字。
  • 符号位只能出现在开头或指数之后,最终必须出现过数字。


复杂度分析

  • 时间复杂度:O(n),其中 n 表示字符串长度。
  • 空间复杂度:O(1),仅使用常数额外空间。
class Solution {
    public boolean isNumber(String s) {
        s = s.trim();
        boolean seenDigit = false;
        boolean seenDot = false;
        boolean seenExp = false;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                seenDigit = true;
            } else if (c == '.') {
                if (seenDot || seenExp) {
                    return false;
                }
                seenDot = true;
            } else if (c == 'e' || c == 'E') {
                if (seenExp || !seenDigit) {
                    return false;
                }
                seenExp = true;
                seenDigit = false;
            } else if (c == '+' || c == '-') {
                if (i > 0 && s.charAt(i - 1) != 'e' && s.charAt(i - 1) != 'E') {
                    return false;
                }
            } else {
                return false;
            }
        }

        return seenDigit;
    }
}
import "strings"

func isNumber(s string) bool {
	s = strings.TrimSpace(s)
	seenDigit := false
	seenDot := false
	seenExp := false

	for i := 0; i < len(s); i++ {
		c := s[i]
		if c >= '0' && c <= '9' {
			seenDigit = true
		} else if c == '.' {
			if seenDot || seenExp {
				return false
			}
			seenDot = true
		} else if c == 'e' || c == 'E' {
			if seenExp || !seenDigit {
				return false
			}
			seenExp = true
			seenDigit = false
		} else if c == '+' || c == '-' {
			if i > 0 && s[i-1] != 'e' && s[i-1] != 'E' {
				return false
			}
		} else {
			return false
		}
	}

	return seenDigit
}

相似题目

题目 难度 考察点
8. 字符串转换整数 (atoi) 中等 字符串
468. 验证IP地址 中等 字符串
224. 基本计算器 困难 解析
227. 基本计算器 II 中等 解析
415. 字符串相加 简单 字符串
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/33182483
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!