确定有限状态自动机

剑指 Offer 20. 表示数值的字符串

image.png

  1. var isNumber = function(s) {
  2. const states = [
  3. { space: 0, sign: 1, digit: 2, dot: 4 },
  4. { digit: 2, dot: 4 },
  5. { digit: 2, dot: 3, e: 5, space: 8},
  6. { digit: 3, e: 5, space: 8 },
  7. { digit: 3 },
  8. { sign: 6, digit: 7 },
  9. { digit: 7 },
  10. { digit: 7, space: 8 },
  11. { space: 8 }
  12. ];
  13. let index = 0;
  14. for (let i=0; i<s.length; i++) {
  15. let cur = s.charAt(i);
  16. if ((/\d/.test(cur))) {
  17. t = 'digit'
  18. } else if (['+', '-'].includes(cur)) {
  19. t = 'sign'
  20. } else if (['e', 'E'].includes(cur)) {
  21. t = 'e'
  22. } else if ('.' == cur) {
  23. t = 'dot'
  24. } else if (' ' == cur) {
  25. t = 'space'
  26. } else {
  27. t = 'unknown'
  28. }
  29. if (!states[index].hasOwnProperty(t)) return false;
  30. index = states[index][t]
  31. }
  32. return [2,3,7,8].includes(index);
  33. };

数学问题

剑指 Offer 66. 构建乘积数组