Created
October 22, 2013 11:05
-
-
Save zsh-89/7098713 to your computer and use it in GitHub Desktop.
Leetcode: Valid Number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isNumber(const char *s) { | |
if (!s) return false; | |
bool sign = true; bool num = false; | |
bool e = true; bool dot = true; int space = 0; | |
char c; | |
while (c=*s++) { | |
if (c != ' ' && space == 2) return false; | |
if (c=='+' || c=='-') { | |
if (!sign) return false; | |
sign = false; space = 1; | |
} else if (isdigit(c)) { | |
sign = false; num = true; | |
space = 1; | |
} else if ((c=='e' || c=='E')) { | |
if (!e || !num) return false; | |
e = false; dot = false; | |
sign = true; num = false; | |
space = 1; | |
} else if (c=='.') { | |
if (!dot) return false; | |
dot = false; sign = false; | |
space = 1; | |
} else if (c==' ') { | |
if (space == 1) space = 2; | |
} else return false; | |
} | |
return num; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
状态机,从头扫到尾。MC的状态机代码比我短,因为他先把头尾的空格干掉了,这样有好有坏
好处是状态少了,不要管space
坏处是破坏了状态机的节操,状态机本来就是从头到位扫一遍得出结果的存在嘛。
space = 0 一开始允许空格
space = 1 进入扫描中间非空格部分
space = 2 中间非空格部分扫描完毕,开始处理结尾的空格
sign 是否允许+/-符号
dot 是否允许小数点
e 是否允许e/E
num 是否出现了数字