65. 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.

分析:http://blog.csdn.net/linhuanmars/article/details/23809661

这是一道检查字符串输入是否为合法的题目。基本规则是按照科学计数法,所以会出现的特殊字符有以下几个:符号位‘+’,‘-’,小数点‘.’,还有‘e’和‘E’,剩下的就只有数字0-9了,其他字符如果出现就是非法字符,返回false。数字字符在哪里出现都是ok的,我们主要考虑几个特殊字符的情况。
对于小数点出现的时候,我们要满足一下这些条件:(1)前面不能有小数点或者‘e’和‘E’;(2)前一位是数字(不能是第一位)或者后一位要是数字(不能是最后一位)。
对于正负号出现的情况,要满足条件:(1)必须是第一位或者在‘e’和‘E’后一位;(2)后一位要是数字。
对于‘e’和‘E’的情况,要满足:(1)前面不能有‘e’和‘E’出现过;(2)不能是第一位(前面没数字科学计数没有意义)或者最后一位(后面没数字就不用写指数了)。
根据上面列举的情况,我们用两个标签和做前后位的判断来实现,算法复杂度比较明显是O(n)的,只需要O(1)的额外空间。代码如下:

代码:http://ideone.com/7MIXt6

[sign] [coefficient] [e or E] [sign] [exponent]

 1 public class Solution {
 2     static boolean isNumber(String s) {
 3         if (s == null || s.trim().length() == 0) return false;
 4         s = s.trim();
 5         int n = s.length(), opCount = 0;
 6         boolean hasE = false, hasNum = false, hasPoint = false;
 7 
 8         // Go through the characters
 9         for (int i = 0; i < n; i++) {
10             char ch = s.charAt(i);
11             // input value
12             if (!(ch <= '9' && ch >= '0' || ch == '.' || ch == 'e' || ch == 'E' || ch == '+' || ch == '-'))
13                 return false;
14 
15             // number
16             if (ch >= '0' && ch <= '9')
17                 hasNum = true;
18 
19             // Case e/E 
20             // (1) 前面不能有‘e’和‘E’出现过;(2)前面不能没数字或者最后一位(后面没数字就不用写指数了)。
21             if (ch == 'e' || ch == 'E') {
22                 if (hasE || !hasNum || i == n - 1) return false;
23                 hasE = true;
24             }
25 
26             // Case decimal point
27             // (1) 前面不能有小数点或者‘e’和‘E’;(2)单独的decimal point 不是valid数字。
28             if (ch == '.') {
29                 if (hasPoint || hasE || i == n - 1 && !hasNum) return false;
30                 hasPoint = true;
31             }
32 
33             // Case sign
34             // (1)必须是第一位或者在‘e’和‘E’后一位;(2)后一位要是数字
35             if (ch == '+' || ch == '-') {
36                 if (opCount == 2 || i == n - 1) return false;
37                 if (i > 0 && !(s.charAt(i - 1) == 'E' || s.charAt(i - 1) == 'e')) return false;
38                 opCount++;
39             }
40         }
41         return true;
42     }
43 }

 

posted @ 2016-08-05 23:11  北叶青藤  阅读(264)  评论(0)    收藏  举报