Question:
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.
--------------------------
Solution 1:
利用现有库,String.replaceAll(),关于的正则表达式问题可以参看前一篇博客。
1 public class Solution { 2 public boolean isNumber(String s) { 3 s=s.trim(); 4 s=s.replaceAll("e|E", "/"); 5 s=s.replaceAll("[a-zA-Z]", "x"); 6 s=s.replaceAll("/", "e"); 7 8 try { 9 Double.parseDouble(s); 10 } catch (Exception e) { 11 // TODO: handle exception 12 13 return false; 14 } 15 16 return true; 17 } 18 } 19
-------------------
Solution2:
Finite-state Machine solution(有限状态机)。
代码转自:https://github.com/AnnieKim/LeetCode/blob/master/ValidNumber.h
1 class Solution { 2 public: 3 bool isNumber(const char *s) { 4 enum InputType {INVALID, SPACE, SIGN, DIGIT, DOT, EXPONENT}; 5 int transitionTable[][SPACEEND] = 6 { /* 0 1 2 3 4 5 */ 7 0, 1, 2, 3, 4, 0, // 0: INVALID 8 0, 1, 2, 3, 4, 0, // 1: SPACE 9 0, 0, 0, 3, 4, 0, // 2: SIGN 10 0, 6, 0, 3, 7, 5, // 3: DIGIT 11 0, 0, 0, 7, 0, 0, // 4: DOT 12 0, 0, 2, 8, 0, 0, // 5: EXPONENT 13 0, 6, 0, 0, 0, 0, // 6: END WITH SPACE 14 0, 6, 0, 7, 0, 5, // 7: DOT AND DIGIT 15 0, 6, 0, 8, 0, 0, // 8: END WITH SPACE OR DIGIT 16 }; 17 18 InputType last = INVALID; 19 while (*s != '