65. Valid Number
难度:Hard
刷题内容
原题连接
- https://leetcode.com/problems/valid-number/
内容描述
Validate if a given string can be interpreted as a decimal number.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
" -90e3 " => true
" 1e" => false
"e3" => false
" 6e-1" => true
" 99e2.5 " => false
"53.5e93" => true
" --6 " => false
"-+3" => false
"95a54e53" => false
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:
Numbers 0-9
Exponent - "e"
Positive/negative sign - "+"/"-"
Decimal point - "."
Of course, the context of these characters also matters in the input.
˼· **- ʱ¼ä¸´ÔÓ¶È: O(N)*- ¿Õ¼ä¸´ÔÓ¶È: O(1)***
ÕâÌâ×öÁËÂù¾ÃµÄ£¬ÌâÄ¿Æäʵ²»ÄÑÖ÷Òª±éÀú×Ö·û´®·ûºÏÒªÇó¼´¿É£¬µ«Òª°ÑËùÓеÄÇé¿ö¶¼¿¼ÂǽøÈ¥¡£±ÈÈçnumberÔÊÐíÇ°ºóÓÐÈô¸É¸ö¿Õ¸ñ£¬¡°.1¡±ºÍ"1.¡±ÊôÓںϷ¨µÄÊý×Ö¡£
class Solution {
public:
void blank(int& i,string& s)
{
while(i < s.length() && s[i] == ' ')
i++;
}
bool firstHalf(int& i,string& s)
{
int num = 0;
for(;i < s.length();++i)
if(isdigit(s[i]))
continue;
else if(s[i] == '.')
{
if(num)
return 0;
num++;
}
else if(s[i] == 'e' || s[i] == ' ')
return 1;
else
return 0;
return 1;
}
bool secondHalf(int& i,string& s)
{
if(i == s.length())
return 0;
if(s[i] =='-' || s[i] == '+')
++i;
if(!isdigit(s[i]))
return 0;
for(;i < s.length();++i)
if(!isdigit(s[i]))
{
if(s[i] == ' ')
return 1;
return 0;
}
return 1;
}
bool isNumber(string s) {
int i = 0;
if(!s.length())
return 0;
blank(i,s);
if(i == s.length())
return 0;
if(s[i] == '-' || s[i] == '+')
++i;
int temp = i;
if(!firstHalf(i,s))
return 0;
if(i == temp)
return 0;
if(i - 1 == temp && s[i - 1] == '.')
return 0;
if(i == s.length())
return 1;
if(s[i] == 'e')
{
i++;
if(!secondHalf(i,s))
return 0;
}
blank(i,s);
return i == s.length();
}
};