[LeetCode 65] Valid Number (通过率最低的一题)

本文介绍了一种判断给定字符串是否为有效数值的方法。该方法通过解析字符串中的数字、小数点和指数部分来确定其是否符合有效数值的标准。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:valid-number



/**
 * 
	Validate if a given string is numeric.
	
	Some examples:
	"0" => true
	" 0.1 " => true
	"abc" => false
	"1 a" => false
	"2e10" => true
	Note: It is intended for the problem statement to be ambiguous. 
	You should gather all requirements up front before implementing one.
 *
 */

public class ValidNumber {

//	1481 / 1481 test cases passed.
//	Status: Accepted
//	Runtime: 214 ms
//	Submitted: 0 minutes ago

	//时间复杂度O(n) 空间复杂度O(1)
    public boolean isNumber(String s) {
		int i = 0;
		s = s.trim(); 				// 去除两端的空格
		boolean hasDecimal = false; // 标记是否已经出现了 小数点(.)
		boolean hasNum = false; 	// 标记之前的字符串是否是数值了
		boolean hasE = false; 		// 标记是否已经出现了 (e)字符
		if (s.length() == 0)
			return false;

		// 判断是否有正负号字符
		if (isSign(s.charAt(0))) {
			i++;
		}
		while (i < s.length()) {
			char c = s.charAt(i);
			
			if (isDigit(c)) {
				if (!hasNum) {
					hasNum = true;
				}
			} else if (isDecimal(c)) {
				if (hasDecimal || hasE) // 整个数值只能出现一个小数点(.); e的指数不能为小数;
					return false;
				hasDecimal = true;
			} else if (isE(c)) {
				// 如果之前的字符已经出现(e)字符,或者(e)出现在整个字符的最前或最后,则都不是一个有效的数值
				if (hasE || !hasNum || (++i) >= s.length())
					return false;
				// 判断指数是否有符号位
				if (!isSign(s.charAt(i)))
					i--;
				hasE = true;
				hasNum = false; // 需要重新寻找一个数值
			} else
				return false; // 如果有 (数字、小数点.、字符e)以外的字符
			i++;
		}
		return hasNum;
    }
    
    public boolean isSign(char c) {
    	return c == '+' || c == '-';
    }
    public boolean isDigit(char c) {
    	return (c - '0' >= 0 && c - '0' <= 9);
	}
    public boolean isDecimal(char c) {
    	return c == '.';
    }
    public boolean isE(char c) {
    	return c == 'e';
    }
    
	public static void main(String[] args) {
		System.out.println(new ValidNumber().isNumber("0"));
		System.out.println(new ValidNumber().isNumber(" 0.1 "));
		System.out.println(new ValidNumber().isNumber("abc"));
		System.out.println(new ValidNumber().isNumber("1 a"));
		System.out.println(new ValidNumber().isNumber("2e10"));
		System.out.println(new ValidNumber().isNumber(".1"));
		System.out.println(new ValidNumber().isNumber("6e6.5"));

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值