首页 > 代码库 > [leetcode] Valid Number
[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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。