官方推荐使用状态机. 但是我觉得使用java里面的函数岂不更香.
https://leetcode-cn.com/problems/valid-number/solution/fei-na-yao-da-jing-gan-sha-zhi-jie-shi-y-boli/
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; } }