Valid Number

描述

Validate if a given string is numeric.

Some examples:

  1. "0" => true
  2. " 0.1 " => true
  3. "abc" => false
  4. "1 a" => false
  5. "2e10" => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

分析

细节实现题。

本题的功能与标准库中的strtod()功能类似。

有限自动机

  1. // Valid Number
  2. // @author 龚陆安 (http://weibo.com/luangong)
  3. // finite automata,时间复杂度O(n),空间复杂度O(n)
  4. class Solution {
  5. public:
  6. bool isNumber(const string& s) {
  7. enum InputType {
  8. INVALID, // 0
  9. SPACE, // 1
  10. SIGN, // 2
  11. DIGIT, // 3
  12. DOT, // 4
  13. EXPONENT, // 5
  14. NUM_INPUTS // 6
  15. };
  16. const int transitionTable[][NUM_INPUTS] = {
  17. -1, 0, 3, 1, 2, -1, // next states for state 0
  18. -1, 8, -1, 1, 4, 5, // next states for state 1
  19. -1, -1, -1, 4, -1, -1, // next states for state 2
  20. -1, -1, -1, 1, 2, -1, // next states for state 3
  21. -1, 8, -1, 4, -1, 5, // next states for state 4
  22. -1, -1, 6, 7, -1, -1, // next states for state 5
  23. -1, -1, -1, 7, -1, -1, // next states for state 6
  24. -1, 8, -1, 7, -1, -1, // next states for state 7
  25. -1, 8, -1, -1, -1, -1, // next states for state 8
  26. };
  27. int state = 0;
  28. for (auto ch : s) {
  29. InputType inputType = INVALID;
  30. if (isspace(ch))
  31. inputType = SPACE;
  32. else if (ch == '+' || ch == '-')
  33. inputType = SIGN;
  34. else if (isdigit(ch))
  35. inputType = DIGIT;
  36. else if (ch == '.')
  37. inputType = DOT;
  38. else if (ch == 'e' || ch == 'E')
  39. inputType = EXPONENT;
  40. // Get next state from current state and input symbol
  41. state = transitionTable[state][inputType];
  42. // Invalid input
  43. if (state == -1) return false;
  44. }
  45. // If the current state belongs to one of the accepting (final) states,
  46. // then the number is valid
  47. return state == 1 || state == 4 || state == 7 || state == 8;
  48. }
  49. };

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/string/valid-number.html