2014.2.27 01:36
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.
Solution:
This is indeed a boring problem. You'll have to be careful with all the possibilities you have in mind.
Here are a few things to take care of:
1. "3." is valid
2. ".49" is valid
3. "2E12" and "-2e-2" are valid, but "E3" is not
4. "000123" is valid
5. "999999999999999999999999999999999" is valid, despite it being well beyond INT_MAX
There're surely other rules to check, but the few cases mentioned above are, in my opinion, more likely to be overlooked.
Total time complexity is O(len(s)). Space complexity is O(1).
Accepted code:
1 // 1CE, 3WA, 1AC, good, but not good enough. 2 #include <cstring> 3 using namespace std; 4 5 class Solution { 6 public: 7 bool isNumber(const char *s) { 8 int i, len; 9 10 if (s == nullptr) { 11 return false; 12 } 13 14 len = strlen(s); 15 // skip the trailing spaces 16 while (len - 1 >= 0 && s[len - 1] == ' ') { 17 --len; 18 } 19 i = 0; 20 21 // skip the leading spaces 22 while (i < len && s[i] == ' ') { 23 ++i; 24 } 25 if (i == len) { 26 return false; 27 } 28 29 // an optional sign 30 if (s[i] == '-' || s[i] == '+') { 31 ++i; 32 } 33 if (i == len) { 34 return false; 35 } 36 37 // the part before 'e' or 'E' 38 int dot_count = 0; 39 int digit_count = 0; 40 while (i < len && s[i] != 'e' && s[i] != 'E') { 41 if (s[i] >= '0' && s[i] <= '9') { 42 ++digit_count; 43 } else if (s[i] == '.') { 44 if (dot_count > 0) { 45 return false; 46 } else { 47 ++dot_count; 48 } 49 } else { 50 return false; 51 } 52 ++i; 53 } 54 if (i == len) { 55 // no 'e' or 'E' 56 if (digit_count > 0) { 57 return true; 58 } else { 59 return false; 60 } 61 } else if (digit_count == 0) { 62 return false; 63 } 64 65 ++i; 66 if (i == len) { 67 // no exponent after 'e' or 'E' 68 // 1.2E 69 return false; 70 } 71 72 if (s[i] == '-' || s[i] == '+') { 73 ++i; 74 } 75 if (i == len) { 76 // no digit after 'e' or 'E' 77 // 1.2E+ 78 // 1.3e- 79 return false; 80 } 81 while (i < len) { 82 if (s[i] >= '0' && s[i] <= '9') { 83 ++i; 84 } else { 85 return false; 86 } 87 } 88 89 return true; 90 } 91 };