简介

官方推荐使用状态机. 但是我觉得使用java里面的函数岂不更香.

参考链接

https://leetcode-cn.com/problems/valid-number/solution/fei-na-yao-da-jing-gan-sha-zhi-jie-shi-y-boli/

code

class Solution {
    public boolean isNumber(String s) {
        for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) != '+' &&s.charAt(i) != '-' &&s.charAt(i) != '.' && (s.charAt(i) > '9' || s.charAt(i) < '0') && (s.charAt(i) != 'e' && s.charAt(i) != 'E')) {
				return false;
			}
		}
        try {
			Double n = Double.parseDouble(s);
		} catch (Exception e) {
			return false;
			// TODO: handle exception
		}
		return true;
    }
}

public boolean isNumber(String s) {
    if (s == null || s.trim().length() == 0 || s.contains("Infinity") ||
            s.contains("f") || s.contains("F") ||
            s.contains("d") || s.contains("D"))
        return false;
    try {
        Double.parseDouble(s);
        return true;
    } catch (Exception e) {
        return false;
    }
}
posted on 2021-06-17 10:29  HDU李少帅  阅读(56)  评论(0编辑  收藏  举报