[leetcode] 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.
https://oj.leetcode.com/problems/valid-number/
思路1:直接处理,一般思路按照'.’分开整数和小数,然后各自判断,情况略复杂。
思路2:自动机,建立好转移函数,代码很直观易懂。
思路3(偷懒):直接写正则表达式(其实正则的匹配背后也是自动机)。
public class Solution { public boolean isNumber(String s) { if (s.trim().isEmpty()) { return false; } String regex = "[-+]?(\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)?"; if (s.trim().matches(regex)) { return true; } else { return false; } } public static void main(String[] args) { System.out.println(new Solution().isNumber("0")); System.out.println(new Solution().isNumber("0.1")); System.out.println(new Solution().isNumber(".1")); System.out.println(new Solution().isNumber("0.")); System.out.println(new Solution().isNumber(".")); System.out.println(new Solution().isNumber("abc")); System.out.println(new Solution().isNumber("1 a")); System.out.println(new Solution().isNumber("2e10")); } }
参考:
http://jane4532.blogspot.com/2013/09/valid-numberleetcode.html
http://www.cnblogs.com/chasuner/p/validNumber.html
http://leetcodenotes.wordpress.com/2013/11/23/leetcode-valid-number/
http://codeganker.blogspot.com/2014/04/valid-number-leetcode.html