问题原始链接 https://leetcode.com/problems/valid-number
验证一个给定的字符串是否是有效的数字。
一些例子:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
注意:题目故意说得很模糊。在实现前你需要自己收集需求。
偷懒写法,直接使用正则表达式。
public class Solution {
public static boolean isNumber(String s) {
if (s == null || s.length() == 0) {
return false;
}
s = s.trim();
if (s.length() == 0) {
return false;
}
return s.matches("[+-]?(\\d+\\.?|\\.\\d+|\\d+\\.\\d+)([eE][+-]?\\d+)?");
}
}