题目:

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.

代码:

class Solution {
public:
bool isNumber(string s) {
if ( s.size()< ) return false;
// escape space from begining and end
int index_begin = ;
int index_end = s.size()-;
while ( s[index_begin]==' ' && index_begin<s.size() ) ++index_begin;
while ( s[index_end]==' ' && index_end>= ) --index_end;
// digit, dot, sign, exp
enum PreChar{ NONPRE, DIGIT, SIGN, EXP, DOT };
enum PreChar preChar = NONPRE;
bool hasDigit = false, hasSign = false, hasExp = false, hasDot = false;
int index = index_begin;
for ( ;index <= index_end; ++index )
{
// space
if ( s[index]==' ') return false;
// digit
if ( s[index]>='' && s[index]<='' ) { hasDigit = true; preChar = DIGIT; continue; }
// sign
if ( s[index]=='+' || s[index]=='-' ){
if ( preChar==EXP || preChar==NONPRE ) { preChar = SIGN; hasSign = true; continue; }
else { return false; }
}
// exp
if ( s[index]=='e' || s[index]=='E' ){
if ( (preChar==DIGIT || preChar==DOT) && !hasExp && hasDigit ) { preChar = EXP; hasExp = true; continue; }
else { return false; }
}
// dot
if ( s[index]=='.' ){
if ( !hasExp && !hasDot && (preChar==DIGIT || preChar==SIGN || preChar==NONPRE ) ) { preChar = DOT; hasDot = true; continue; }
else { return false; }
}
// illegal input char
return false;
}
// end with digit or dot
return preChar==DIGIT || (preChar==DOT && hasDigit);
}
};

tips:

主要基于这篇blog的思路(http://blog.unieagle.net/2012/11/06/leetcode题目:valid-number/)。在其基础上,对逻辑进行了更系统的梳理和简化。

思路如下:

1. 首先排除字符串首尾的space,这样可以简化判断逻辑(只要在后面的字符串中再出现空格,就一定不是合法数字)

2. 判断剩余的字符串中出现dot('.'), sign('+','-'), exp('e','E'), digit(0~9)是否是合法的。判断的核心逻辑有两个:

  a. 上一个出现的字符是什么(即代码中的preChar)

  b. dot,sign,exp,digit,是否在之前出现过

这种代码逻辑的好处是:只要认准了两个核心判断逻辑,在这两个核心逻辑之内修修补补,就可以不断地刷test case直到AC。

如果以后有类似的问题,状态条件非常多的,但是输入条件相对固定;并且又需要根据序列化输入条件判断的。

可以多设定几类变量逻辑变量,然后通过判断几类逻辑变量的取值来往下进行;即使不能一次bug free,但是总可以把逻辑补完全。

=====================================================

之前一直看网上的有限状态机(FSM)的做法(http://www.cnblogs.com/chasuner/p/validNumber.html),这种思路的代码非常consice。

FSM怎么运转的,解释的很清晰;但是FSM中这0~8的状态是怎么来的,我并没有看懂,所以只好选择比较一般的方法。

================================================

第二次过这道题,直接照着上次写的代码记忆重复了一下。

class Solution {
public:
bool isNumber(string s) {
if ( s.size()< ) return false;
// remove blanks both begin and end
int i_begin = ;
int i_end = s.size()-;
while ( s[i_begin]==' ' && i_begin<i_end ) ++i_begin;
while ( s[i_end]==' ' && i_begin<i_end ) --i_end;
enum PreType{ NONE, DIGIT, EXP, SIGN, DOT };
enum PreType preType = NONE;
bool hasDigit=false, hasExp=false, hasSign=false, hasDot=false;
int i = i_begin;
for ( ;i<=i_end; ++i )
{
// blank
if ( s[i]==' ' )
{
return false;
}
// digit
else if ( s[i]>='' && s[i]<='' )
{
hasDigit = true; preType = DIGIT;
}
// sign
else if ( s[i]=='+' || s[i]=='-' )
{
if ( preType==EXP || preType==NONE )
{
hasSign=true; preType = SIGN;
}
else
{
return false;
}
}
// exp
else if ( s[i]=='e' || s[i]=='E' )
{
if ( (preType==DIGIT || preType==DOT) && !hasExp && hasDigit )
{
hasExp=true; preType=EXP;
}
else
{
return false;
}
}
// dot
else if ( s[i]=='.' )
{
if( !hasExp && !hasDot && (preType==DIGIT || preType==SIGN || preType==NONE ) )
{
hasDot=true; preType = DOT;
}
else
{
return false;
}
}
else
{
return false;
}
}
return preType==DIGIT || (preType==DOT && hasDigit);
}
};

【Valid Number】cpp的更多相关文章

  1. 【Valid Sudoku】cpp

    题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...

  2. 【Valid Palindrome】cpp

    题目: Given a string, determine if it is a palindrome, considering only alphanumeric characters and ig ...

  3. 【Valid Parentheses】cpp

    题目: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the ...

  4. 【Palindrome Number】cpp

    题目: Determine whether an integer is a palindrome. Do this without extra space. click to show spoiler ...

  5. 【Single Number】cpp

    题目: Given an array of integers, every element appears twice except for one. Find that single one. No ...

  6. 【Longest Valid Parentheses】cpp

    题目: Given a string containing just the characters '(' and ')', find the length of the longest valid ...

  7. 【Letter Combinations of a Phone Number】cpp

    题目: Given a digit string, return all possible letter combinations that the number could represent. A ...

  8. 【Gray Code】cpp

    题目: The gray code is a binary numeral system where two successive values differ in only one bit. Giv ...

  9. 【Sort Colors】cpp

    题目: Given an array with n objects colored red, white or blue, sort them so that objects of the same ...

随机推荐

  1. Wpf实现图片自动轮播自定义控件

    近来,公司项目需要,需要写一个自定义控件,然后就有下面的控件产生.样式没有定义好,基本功能已经实现.1.创建为自定义控件的XAML页面.下面为后台代码 using System; using Syst ...

  2. 软件工程 speedsnail 第二次冲刺5

    20150522 完成任务:蜗牛帧数变化已经实现,行走的蜗牛具有了动态的视觉效果: 遇到问题: 问题1 帧数大小根据人眼来设置 解决1 除29余0到14的为第一帧 明日任务: 蜗牛碰撞身体翻转

  3. 01-实现图片按钮的缩放、动画效果(block的初步应用)

    #import "ViewController.h" #define kDelta 60 @interface ViewController () @end @implementa ...

  4. Java应用架构的演化之路

    Java应用架构的演化之路 当我们架设一个系统的时候通常需要考虑到如何与其他系统交互,所以我们首先需要知道各种系统之间是如何交互的,使用何种技术实现. 1. 不同系统不同语言之间的交互 现 在我们常见 ...

  5. python restful 框架之 eve 外网访问设置

    官网地址: http://python-eve.org/ 配合mongodb进行crud使用起来很方便,但是部署的时候遇到一个问题,按照官网和Deom说的,servername使用 '127.0.0. ...

  6. php ajax提交post请求出现数组被截断情况的解决方法

    一.场景 今天做保存专题商品列表的时候发现,前端明明有2300多条数据,但是实际服务端接受存入数据库才166条 二.解决过程 经过调试发现前端页面提交post请求时数据量是正确的,但到服务端只能接受到 ...

  7. 用开源中国(oschina)Git管理代码(整合IntelliJ 13.1.5)

    简介 开源中国提供了Git服务(地址:http://git.oschina.net/),在速度上比国外的github要快很多.使用了一段时间,感觉很不错.oschina git提供了演示平台,可以运行 ...

  8. 2)main函数在执行前和执行后有哪些操作

    main函数执行之前,主要就是初始化系统相关资源:      1. 设置栈指针      2. 初始化static静态和global全局变量,即data段的内容      3. 将未初始化部分的全局变 ...

  9. List集合实战总结

    //构造被分隔的集合 List<object> list = new List<object>(); for (int i = 0; i <= 100; i++) { l ...

  10. Mysql 简单问题汇总(持续更新)

    主从架构相关问题 问题现象:从机连接主机时报错 [ERROR] Slave I/O: error connecting to master 'repl@192.168.0.50:3306' - ret ...