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

 思路:一般解法感觉好麻烦,所以又去看大神的解法了,汗!有限状态机,额,看不明白,正则表达式,代码简单的,我又看不明白。幸好找到了自己看的懂的,参考了Yu's garden九章算法。大致的思路如下:设置三个flag:num、exp、dot表示当前字符之前是否出现相应数字、' e  '、‘ . ’的情况,true为出现过,false没有出现过,有以下几种情况,分别表示出现对应字符时,这个字符串为数字的条件:

1)出现' e ',则前面出现的要有数字,且后面也要有数字。如“ 5.6e8”;

2)出现' . ',那么是一个小数,则前面不可以有 ' . '和 ‘ e ’;

3)出现 ' + '、' - ',那出现的情况,只能是第一个或者前一个字符为' e ',如“5.7e+6”;

4)出现其他情况要返回false;

刚开始,三个flag都设置为false,说明从头开始时,三者都没出现。

代码如下:

 1 class Solution {
 2 public:
 3     bool isNumber(const char *s) 
 4     {
 5         int len=strlen(s);
 6         int i=0,end=len-1;
 7 
 8         //除去首尾的空格
 9         while(i<=end&&s[i]==' ')
10             i++;
11         if(i>len-1) return false;
12 
13         while(end>=i&&s[end]==' ')
14             end--;
15         //结束
16 
17         if(s[i]=='+'||s[i]=='-')    //首字符为'+'、'-'的情况
18             i++;
19         
20         bool num=false;
21         bool dot=false;
22         bool exp=false;
23 
24         while(i<=end)
25         {
26             char c=s[i];
27             if(c=='e')
28             {
29                 if(exp|| !num)
30                     return false;
31                 exp=true;
32                 num=false;
33             }
34             else if(s[i]>='0'&&s[i]<='9')
35                 num=true;
36             else if(c=='.')
37             {
38                 if(exp||dot)
39                     return false;
40                 dot=true;
41             }
42             else if(c=='+'||c=='-')     //字符串中间遇到'+'、'-'的情况
43             {
44                 if(s[i-1] !='e')
45                     return false;
46             }
47             else                        //中间有空格或者有其他字母或字符的情况
48                 return false;
49             
50             i++;            
51         }
52         return num;
53 
54     }
55 };
posted @ 2017-06-27 16:51  王大咩的图书馆  阅读(262)  评论(0编辑  收藏  举报