LeetCode: Valid Number 解题报告

时间:2023-03-09 04:22:50
LeetCode: Valid Number  解题报告

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.

SOLUTION 1:

我们设置3个FLAG:

1. num

2. exp

3. dot

有以下情况:

(1). 出现了e,则前面要有digit,不能有e. 并且后面要有digit.

(2). 出现了.  那么是一个小数,那么前面不可以有.和e

(3). 出现了+, - 那么它必须是第一个,或者前一个是e,比如" 005047e+6"

实际的代码实现如下,相当的简洁。

感谢答案的提供者:http://www.ninechapter.com/solutions/valid-number/

大神哇哇哇!

 public class Solution {
public boolean isNumber(String s) {
if (s == null) {
return false;
} // cut the leading spaces and tail spaces.
String sCut = s.trim(); /*
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
*/ int len = sCut.length(); boolean num = false;
boolean exp = false;
boolean dot = false; for (int i = 0; i < len; i++) {
char c = sCut.charAt(i);
if (c == 'e') {
if (!num || exp) {
return false;
}
exp = true;
num = false; // Should be: 2e2 , so there should be number follow "e"
} else if (c <= '9' && c >= '0') {
num = true;
} else if (c == '.') {
if (exp || dot) { // can't be: e0.2 can't be: ..
return false;
}
dot = true;
} else if (c == '+' || c == '-') {
if (i != 0 && sCut.charAt(i - 1) != 'e') { // filter : " 005047e+6", this is true.
return false;
}
} else {
// invalid character.
return false;
}
} return num;
}
}

请至主页君的GitHUB: https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/IsNumber.java

用正则其实也可以哦:

推荐一些较好的教程:

http://developer.51cto.com/art/200912/166310.htm

http://luolei.org/2013/09/regula-expression-simple-tutorial/

http://net.tutsplus.com/tutorials/php/regular-expressions-for-dummies-screencast-series/

http://deerchao.net/tutorials/regex/regex.htm

主页君就不写了,因为觉得正则实在是写不出来在面试时,真的太复杂了。

给个大神写好的正则的解答:

http://blog.csdn.net/fightforyourdream/article/details/12900751?reload