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. // finite automata,时间复杂度O(n),空间复杂度O(n)
  3. public class Solution {
  4. public boolean isNumber(String s) {
  5. int[][] transitionTable = new int[][] {
  6. { -1, 0, 3, 1, 2, -1 }, // next states for state 0
  7. { -1, 8, -1, 1, 4, 5 }, // next states for state 1
  8. { -1, -1, -1, 4, -1, -1 }, // next states for state 2
  9. { -1, -1, -1, 1, 2, -1 }, // next states for state 3
  10. { -1, 8, -1, 4, -1, 5 }, // next states for state 4
  11. { -1, -1, 6, 7, -1, -1 }, // next states for state 5
  12. { -1, -1, -1, 7, -1, -1 }, // next states for state 6
  13. { -1, 8, -1, 7, -1, -1 }, // next states for state 7
  14. { -1, 8, -1, -1, -1, -1 } // next states for state 8
  15. };
  16. int state = 0;
  17. for (int i = 0; i < s.length(); ++i) {
  18. final char ch = s.charAt(i);
  19. InputType inputType = InputType.INVALID;
  20. if (Character.isSpaceChar(ch))
  21. inputType = InputType.SPACE;
  22. else if (ch == '+' || ch == '-')
  23. inputType = InputType.SIGN;
  24. else if (Character.isDigit(ch))
  25. inputType = InputType.DIGIT;
  26. else if (ch == '.')
  27. inputType = InputType.DOT;
  28. else if (ch == 'e' || ch == 'E')
  29. inputType = InputType.EXPONENT;
  30. // Get next state from current state and input symbol
  31. state = transitionTable[state][inputType.ordinal()];
  32. // Invalid input
  33. if (state == -1) return false;
  34. }
  35. // If the current state belongs to one of the accepting (final) states,
  36. // then the number is valid
  37. return state == 1 || state == 4 || state == 7 || state == 8;
  38. }
  39. enum InputType {
  40. INVALID, // 0
  41. SPACE, // 1
  42. SIGN, // 2
  43. DIGIT, // 3
  44. DOT, // 4
  45. EXPONENT, // 5
  46. NUM_INPUTS // 6
  47. }
  48. }

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