题目:
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.
思路:
基本思路是类似词法分析器一样,一次读取每个字符并写入一个栈中。最后将栈中的结果与指定的语法匹配,若匹配正确则返回成功;否则返回失败。为了简单起见,我们用如下字符表示字符集:
F表示符号
N表示数字
.表示小数点
E表示10进制符号
_表示空格
代码:
class Solution {
public:
bool isNumber(const char *s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len = 0;
int data[10];
for(int i = 0; i < 10; i++)
{
data[i] = 'O';
}
for(int i = 0; s[i] != '\0'; i++)
{
if(len == 0 && s[i] ==' ')
{
continue;
}
else if(s[i] == '+' || s[i] == '-')
{
data[len++] = 'F';
}
else if(len == 0 && s[i] >= '0' && s[i] <= '9')
{
data[len++] = 'N';
}
else if(len == 0 && s[i] == '.')
{
data[len++] = '.';
}
else if(len > 0 && s[i] >= '0' && s[i] <= '9')
{
if(data[len - 1] == 'N')
{
continue;
}
else if(data[len - 1] == ' ')
{
return false;
}
else
{
data[len++] = 'N';
}
}
else if(len > 0 && (s[i] == 'E' || s[i] == 'e'))
{
data[len++] = 'E';
}
else if(len > 0 && s[i] == '.')
{
data[len++] = '.';
}
else if(len > 0 && s[i] ==' ')
{
if(data[len - 1] == ' ')
{
continue;
}
else
{
data[len++] = ' ';
}
}
else
{
return false;
}
}
if(data[len-1] == ' ')
{
len--;
}
vector<string> pattern;
pattern.push_back("N");
pattern.push_back("FN");
pattern.push_back("N.N");
pattern.push_back("FN.N");
pattern.push_back(".N");
pattern.push_back("F.N");
pattern.push_back("NEN");
pattern.push_back("FNEN");
pattern.push_back("NEFN");
pattern.push_back("FNEFN");
pattern.push_back("N.");
pattern.push_back("FN.");
pattern.push_back("N.NEN");
pattern.push_back("FN.NEN");
pattern.push_back("N.NEFN");
pattern.push_back("FN.NEFN");
pattern.push_back("N.EN");
pattern.push_back("FN.EN");
pattern.push_back("N.EFN");
pattern.push_back("FN.EFN");
pattern.push_back(".NEN");
pattern.push_back("F.NEN");
pattern.push_back(".NEFN");
pattern.push_back("F.NEFN");
for(int i = 0; i < pattern.size(); i++)
{
if(len == pattern[i].size())
{
bool match = true;
for(int j = 0; j < len; j++)
{
if(pattern[i][j] != data[j])
{
match = false;
break;
}
}
if(match)
return true;
}
}
return false;
}
};