LeetCode 65. Valid Number

原题链接在这里:https://leetcode.com/problems/valid-number/

题目:

Validate if a given string can be interpreted as a decimal number.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
" -90e3   " => true
" 1e" => false
"e3" => false
" 6e-1" => true
" 99e2.5 " => false
"53.5e93" => true
" --6 " => false
"-+3" => false
"95a54e53" => false

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:

  • Numbers 0-9
  • Exponent - "e"
  • Positive/negative sign - "+"/"-"
  • Decimal point - "."

Of course, the context of these characters also matters in the input.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

题解:

用多个flag来检测. 原string trim后从e拆开,前面部分可以有dot, 后面部分不可以有dot. 

Note: dot后面可能没有数字. After e, there must be digit.

Time Complexity: O(s.length()).

Space: O(1).

AC Java:

 1 class Solution {
 2     public boolean isNumber(String s) {
 3         if(s == null || s.length() == 0){
 4             return false;
 5         }
 6 
 7         boolean eSeen = false;
 8         boolean dotSeen = false;
 9         boolean digitSeen = false;
10         s = s.trim().toLowerCase();
11         for(int i = 0; i < s.length(); i++){
12             char c = s.charAt(i);
13             if(c == '+' || c == '-'){
14                 if(i != 0 && s.charAt(i - 1) != 'e'){
15                     return false;
16                 }
17             }else if(Character.isDigit(c)){
18                 digitSeen = true;
19             }else if(c == '.'){
20                 if(dotSeen || eSeen){
21                     return false;
22                 }
23 
24                 dotSeen = true;
25             }else if(c == 'e'){
26                 if(eSeen || !digitSeen){
27                     return false;
28                 }
29 
30                 eSeen = true;
31                 digitSeen = false;
32             }else{
33                 return false;
34             }
35         }
36 
37         return digitSeen;
38     }
39 }

 

posted @ 2015-11-10 01:48  Dylan_Java_NYC  阅读(217)  评论(0编辑  收藏  举报