题意理解
给定一个字符串,判断是不是数值,数值包括小数,整数,科学计数格式三种,可以带+-;
问题分析
动规,一层层判断,包括整数判断,小数判断,
其他
花了好长时间,思路要整理整理,虽然做出来了,不过很多条件没有考虑到。
链接
class Solution {
public:
bool isNumber(string s) {
int len = s.size();
int low = 0, high = len - 1;
//cout << "start" << endl;
//去前空格
while(low < high) {
if (s[low] == ' ') low++;
else break;
}
//cout << "process" << endl;
//去后空格
while(high > low) {
if (s[high] == ' ') high--;
else break;
}
//cout << "process2" << endl;
//找eE
if (s[low] == 'E' || s[low] == 'e') return false;
//cout << "1" << endl;
int posE = low;
while(posE < high) {
if (s[posE] != 'E' && s[posE] != 'e') posE++;
else break;
}
if (posE == high) {
if (s[low] == '+' || s[low] == '-') {
return isPositive(s,low+1,high) || isDecimal(s,low+1,high);
}
return isPositive(s,low,high) || isDecimal(s,low,high);
}
else {
if (s[low] == '+' || s[low] == '-') {
if (s[posE+1] == '+' || s[posE+1] == '-') {
return (isPositive(s,low+1,posE-1) || isDecimal(s,low+1,posE-1)) && isPositive(s,posE+2,high);
}
else {
return (isPositive(s,low+1,posE-1) || isDecimal(s,low+1,posE-1)) && isPositive(s,posE+1,high);
}
}
else {
if (s[posE+1] == '+' || s[posE+1] == '-') {
return (isPositive(s,low,posE-1) || isDecimal(s,low,posE-1)) && isPositive(s,posE+2,high);}
else {
return (isPositive(s,low,posE-1) || isDecimal(s,low,posE-1)) && isPositive(s,posE+1,high);
}
}
}
return false;
}
int isPositive(string s, int low, int high) {
//cout << "isPositive low high " << low << '\t' << high << endl;
if (low > high) return false;
//if (s[low] == '+'|| s[low] == '-') low++;
if (s[low] < '0' || s[low] > '9') return false;
if (low == high) return true;
return isPositive(s, low+1, high);
}
int isDecimal(string s, int low, int high) {
//cout << "isDecimal low high " << low << '\t' << high << endl;
if (low > high) return false;
//if (s[low] == '+' || s[low] == '-') low++;
if (s[low] == '.') return isPositive(s, low+1, high);
if (s[high] == '.') return isPositive(s, low, high-1);
int dotPos = low;
while (dotPos < high) {
if (s[dotPos] == '.') {
break;
}
dotPos++;
}
if (dotPos == high) return false; //没有小数点
return isPositive(s, low, dotPos-1) && isPositive(s, dotPos+1, high);
}
};