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.
題意:判斷一個string是否是有效數字。
難度是hard,這個hard不在於有多難寫,而在於有很多莫名其妙的有效數字。“這樣都行!?”“你是在逗我嗎???”“到底有完沒完!”各種奇葩數字層出不窮,就這樣在補漏洞的過程中竟然AC了~o(╯□╰)o~凸
總結了一下數字特性如下:
1、字符串前後可以存在空格,中間不可以有
2、字母只可以有e(我只判斷了小寫沒有判斷大寫竟然也可以,或者說默認爲只有小寫才正確?)
3、e前後一定要有非0的數字
4、e後面不可以有小數點
5、e與小數點之間要有數字
6、e後面可以有+或-(+、-前面一定要爲e)
7、最後一個字符不可以爲’+’ 、’-‘和 ‘e’
8、e和小數點 . 只可以出現一次
其實規則沒有這麼複雜,只是在一次次補漏洞中越來越多。
bool isNumber(string s) {
if(s.length()==0)
{
return false;
}
int i=0;
while(i<s.length()&&s[i]==' ')
{
i++;
}
if(i==s.length())
{
return false;
}
int j=s.length()-1;
while(j>=i&&s[j]==' ')
{
--j;
}
if(s[i]=='+'||s[i]=='-')
{
i++;
}
stack<char> st;
bool e=false;
bool d=false;
bool al=false;
int len=j-i+1;
while(i<=j)
{
if(s[i] >='0' && s[i] <='9')
{
if(s[i]>'0'&&!e)
{
al=true;
}
if(s[i]>'0'&&e)
{
al=true;
}
st.push(s[i]);
}
else if(s[i]=='.'&&!e&&!d)
{
st.push(s[i]);
d=true;
}
else if(s[i]=='e'&&!e)
{
if(st.empty())
{
return false;
}
else if(st.top()=='.'&&!al)
{
return false;
}
st.push(s[i]);
e=true;
}
else if(s[i]=='+'||s[i]=='-')
{
if(!st.empty())
{
if(st.top()=='e')
{
st.push(s[i]);
}
else{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
i++;
}
if(e&&!al)
{
return false;
}
if(st.top()=='e'||st.top()=='+'||st.top()=='-')
{
return false;
}
if(len==1&&st.top()=='.')
{
return false;
}
return true;
}