[LeetCode] Valid Number

本文提供了两种方法来判断一个字符串是否代表有效的数字:一种使用正则表达式的方法,另一种是非正则表达式的迭代方法。通过这两种方法,可以有效地检测字符串是否符合数字格式的要求。

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

这里看来的好的解答

public boolean isNumber(String s) {  
        if(s.trim().isEmpty()){  
            return false;  
        }  
        /*
        re* Matches 0 or more occurrences of preceding expression.
        re+ Matches 1 or more of the previous thing
        re? Matches 0 or 1 occurrence of preceding expression.
        a| b    Matches either a or b.
        [...]   Matches any single character in brackets.
        \d  Matches digits. Equivalent to [0-9].
        */
        String regex = "[-+]?(\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)?";  
        if(s.trim().matches(regex)){  
            return true;  
        }else{  
            return false;  
        }  
    }  

九章算法给了一个non regex解答

public class Solution {
    public boolean isNumber(String s) {
        int len = s.length();
        int i = 0, e = len - 1;
        while (i <= e && Character.isWhitespace(s.charAt(i))) i++;
        if (i > len - 1) return false;
        while (e >= i && Character.isWhitespace(s.charAt(e))) e--;
        // skip leading +/-
        if (s.charAt(i) == '+' || s.charAt(i) == '-') i++;
        boolean num = false; // is a digit
        boolean dot = false; // is a '.'
        boolean exp = false; // is a 'e'
        while (i <= e) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                num = true;
            }
            else if (c == '.') {
                if(exp || dot) return false;
                dot = true;
            }
            else if (c == 'e') {
                if(exp || num == false) return false;
                exp = true;
                num = false;
            }
            else if (c == '+' || c == '-') {
                if (s.charAt(i - 1) != 'e') return false;
            }
            else {
                return false;
            }
            i++;
        }
        return num;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值