当前位置:   article > 正文

【LeetCode 65】Valid Number (Python)_python leetcode 65

python leetcode 65

有限状态机:https://blog.csdn.net/suwei19870312/article/details/12094233

 

  1. class Solution(object):
  2. def isNumber(self, s):
  3. """
  4. :type s: str
  5. :rtype: bool
  6. """
  7. if not s:
  8. return False
  9. INVALID = 0
  10. SPACE = 1
  11. SIGN = 2
  12. DIGIT = 3
  13. DOT = 4
  14. E = 5
  15. transition = [
  16. [-1,0,3,1,2,-1],
  17. [-1,8,-1,1,4,5],
  18. [-1,-1,-1,4,-1,-1],
  19. [-1,-1,-1,1,2,-1],
  20. [-1,8,-1,4,-1,5],
  21. [-1,-1,6,7,-1,-1],
  22. [-1,-1,-1,7,-1,-1],
  23. [-1,8,-1,7,-1,-1],
  24. [-1,8,-1,-1,-1,-1]
  25. ]
  26. state = 0
  27. for i in s:
  28. if i == ' ':
  29. idx = SPACE
  30. elif i == '-' or i == '+':
  31. idx = SIGN
  32. elif i >= '0' and i <= '9':
  33. idx = DIGIT
  34. elif i == '.':
  35. idx = DOT
  36. elif i == 'E' or i == 'e':
  37. idx = E
  38. else:
  39. idx = INVALID
  40. state = transition[state][idx]
  41. if state == -1:
  42. return False
  43. return state == 1 or state == 4 or state == 7 or state == 8

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/72053
推荐阅读
相关标签
  

闽ICP备14008679号