leetcode - Valid Number
题目:
Valid Number
Validate if a given string is numeric.
Some examples:
"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
class Solution { public: bool isNumber(string s) { if (s.empty()) return false; //删除开头和结尾的空格 //删除开头空格 if (s[0] == ' ') { int i = 1; while (i<s.size() && s[i] == ' ') ++i; s.erase(s.begin(), s.begin() + i); } //删完开头空格后若为空,则返回假 if (s.empty()) return false; int size = s.size(); //删除结尾空格 if (s[size - 1] == ' ') { int i = size - 2; while (i >= 0 && s[i] == ' ') --i; if (i<0) return false; s.erase(s.begin() + i + 1, s.end()); } //删除结尾空格后,若为空或以'e'开头,返回假 if (s.empty() || s[0] == 'e' || s[0] == 'E') return false; //若仍然有空格,返回假 if (s.find(" ") != string::npos) return false; size = s.size(); int index = 0; if (s[index] == '+' || s[index] == '-') ++index; //仅仅有加减号,返回假 if (index == size) return false; //若第一个小数点前有数字,docbeforenum为真 bool docbeforenum = false; if (s[index] >= '0' && s[index] <= '9') docbeforenum = true; scanNumber(s, index); //一个整数,返回真 if (index == size) return true; bool res = true; //小数 if (s[index] == '.') { ++index; //'.'是字符串最后一位时。'.'前有数字则返回真,否则返回假 if (index == size) { return docbeforenum; } //'.'后紧跟着非数字时 if (s[index]<'0' || s[index]>'9') { if ((s[index] == 'e' || s[index] == 'E') && docbeforenum) { // “数字.e” 的形式。继续推断 } else return false; } scanNumber(s, index); //小数的形式,返回真 if (index == size) return true; if (s[index] == 'e' || s[index] == 'E') res = isExp(s, index); } else if (s[index] == 'e' || s[index] == 'E') { // 'e'前没有数字,返回假 if (docbeforenum == false) return false; res = isExp(s, index); } else res = false; return res && s[index] == '\0'; } //遇到数字则往后走 void scanNumber(const string &s, int &index) { int size = s.size(); while (index<size && s[index] >= '0' && s[index] <= '9') ++index; } //推断以'e'开头的字符串能否代表指数 bool isExp(const string &s, int &index) { ++index; int size = s.size(); //仅仅有一个'e',返回假 if (index == size) return false; if (s[index] == '+' || s[index] == '-') ++index; //'e'后没有数字,返回假 if (index == size || s[index]<'0' || s[index]>'9') return false; scanNumber(s, index); return true; } };