0065.cpp (1428B)
1 class Solution { 2 using it_t = string::const_iterator; 3 4 static bool validSign(it_t &pos, const it_t &end) { 5 if (*pos == '-' || *pos == '+') { 6 pos++; 7 if (find(pos, end, '-') != end || find(pos, end, '+') != end) { 8 return false; 9 } 10 } 11 12 return pos != end; 13 } 14 15 static bool validDigit(const it_t &pos, const it_t &end) { 16 return all_of(pos, end, [](char c) { return isdigit(c); }); 17 } 18 19 static bool isDecimal(const string &s) { 20 auto pos = begin(s); 21 22 if (!validSign(pos, end(s))) return false; 23 if (string(pos, end(s)) == ".") return false; 24 25 auto dot = find(pos, end(s), '.'); 26 return validDigit(pos, dot) && validDigit(dot + 1, end(s)); 27 } 28 29 static bool isInteger(const string &s) { 30 auto pos = begin(s); 31 if (!validSign(pos, end(s))) return false; 32 return validDigit(pos, end(s)); 33 } 34 35 public: 36 bool isNumber(const string &s) const { 37 auto e = s.find('e'), E = s.find('E'); 38 39 if (E != string::npos) swap(e, E); 40 if (e != string::npos) { 41 const string first = s.substr(0, e); 42 const string second = s.substr(e + 1); 43 return !first.empty() && !second.empty() && isInteger(second) && 44 (isDecimal(first) || isInteger(first)); 45 } 46 47 return isDecimal(s) || isInteger(s); 48 } 49 };