Valid Number -linkedin

来源:互联网 发布:ikbc mac 设置键位 编辑:程序博客网 时间:2024/04/29 23:19

Valid Number

 Total Accepted: 18735 Total Submissions: 167562My Submissions

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.

click to show spoilers.

Update (2014-12-06):
New test cases had been added. Thanks unfounder's contribution.

Hide Tags
 Math String
Have you met this question in a real interview? 
Yes
 
No


Refer:

http://blog.csdn.net/kenden23/article/details/18696083


本题5星级接近6星级的题目,本题是十分麻烦的题目,情况是非常多,网上也很多方法,其中最有效,优雅的方法是有限状态自动机(Finite automata machine)。其他一般方法都会十分复杂,而代码不能算优雅。为此我也曾经专门修了一个automata的知识。

只要设计好Finite Automata Machine之后,写程序就可以很优雅,很简单了。

但是,问题是要构造一个Finite Automata也是十分麻烦的事情,我画了一张A4纸,像蜘蛛网一样的,故此就不贴出来了,也搞了一两个小时,要多练练automata才能快起来吧


注释一下本题分多少状态吧:

0初始无输入或者只有space的状态
1输入了数字之后的状态
2前面无数字,只输入了Dot的状态
3输入了符号状态
4前面有数字和有dot的状态
5'e' or 'E'输入后的状态
6输入e之后输入Sign的状态
7输入e后输入数字的状态
8前面有有效数输入之后,输入space的状态

共9种状态了,难设计的是6,7,8状态。

分好之后就好办了,设计出根据输入进行状态转换就OK了。


这里的输入可以分:

INVALID,  // 0 Include: Alphas, '(', '&' ans so on
SPACE,  // 1
SIGN, // 2 '+','-'
DIGIT,  // 3 numbers
DOT, // 4 '.'
EXPONENT,  // 5 'e' 'E'

然后就是画蜘蛛网吧,什么状态可以转换到什么状态的。






0 0
原创粉丝点击