LeetCode 65. 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.
分析
这道题是要我们判断字符串是否为合规的数字。
无非是枚举出所有合规的类型,但这里我为了使代码更为简便,使用了模式匹配。
mod == 0时(模式为0时):代表我还什么都没输入
mod == 1时:代表为数字 + ‘.’ 的类型
mod == 2时:代表为仅有’.’的类型
mod == 3时,代表为数字+’e’的类型
现在·我们分析一下上面的模式,当mod == 0时,代表前面可以接受任意个空字符,可以接受1个正负号。若接受了数字+’.’转为mod1,接受了’.’转为mod2,接受了数字+’e’转为mod3。
当mod == 1时,代表不可以接受正负号,不可以接受’.’,可以接受’e’或数字+’e’,并转为mod3,还可以什么都不接受。
当mod == 2时,代表至少接受1个数字,不可以接受正负号,不可以接受’.’,可以接受’e’或数字+’e’,并转为mod3。
当mod == 3时,代表至少接受1个数字,可以接受一个正负号,不可以接受’.’。
还有一些不管什么模式都无法通过的:
两个有效字符中间插了空格
数字后面跟着正负号
出现了不合法字符
正负号连用
还有一些不管什么格式都允许的:
- 末尾有空格
代码实现
class Solution {
public:
bool isNumber(string s) {
return isNumber_iterator(s,0,-1);
}
bool isNumber_iterator(string& s,int mod,int now_index) {
// mod == 0: ()
// mod == 1: (num).
// mod == 2: ().
// mod == 3: (num)e
bool result = false;
bool TRUE = true;
bool sign = false;
for (int index = now_index + 1; index < s.length(); index++)
{
if (!(is_number(s[index])))
{
//该位非数字
if (!result && s[index] == ' ')
{
//该位为空格且前面没数字
//该位为空格且前面有有效字符
if(mod || sign)TRUE = false;
continue;
}
else if (s[index] == ' ')
{
//该位为空格且前面有数字
TRUE = false;
continue;
}
else if (s[index] == '-' || s[index] == '+')
{
//该位为-||+
if (result || sign)return false;
sign = true;
if(mod == 0|| mod == 3)
continue;
else return false;
}
else if (mod == 0 && s[index] == '.')
{
//该位为'.'
if (!TRUE)return false;
if(result)return isNumber_iterator(s, 1, index);
else return isNumber_iterator(s, 2, index);
}
else if ((mod == 0 || mod == 1 || mod == 2) && (s[index] == 'e' || s[index] == 'E'))
{
//该位为'e'
if (!TRUE)return false;
if(result || mod == 1)return isNumber_iterator(s, 3, index);
else return false;
}
else return false;
}
else
{
if (!TRUE) return false;
result = TRUE;
}
}
if (mod == 1)return true;
return result;
}
bool is_number(char ch) {
return ch >= 48 && ch <= 57;
}
};