【leetcode刷题】65 Valid number (Python)

原题链接
https://leetcode.com/problems/valid-number
解题思路
我自己写这段代码的时候很头大,总是考虑不全所有状态,最后迷迷糊糊地通过了测试。上网查了以后发现这道题大神们都用的有穷状态机方法,这里附上链接供自己查看、学习
https://www.cnblogs.com/zuoyuan/p/3703075.html
然后附上我乱七八糟的代码,虽然很没有逻辑,但还是记录一下好了。
主要是这样考虑的:

  • 去除前后space
  • 从’e’对str切分:str中有e,切分过后的列表s长度为2,否则为1
  • 对于s[0]:
  • 可以是±/./number开头。±开头,下一位只能是./number;.开头,下一位只能是number;number开头,下一位可以是number或.
  • 除了开头以外,如果没有出现过.,下一位可以是.;否则下一位只能是number
  • 对于s[1](s的len为2才考虑):
  • 第一位可以是±或number;从第二位开始只能是number

代码

class Solution(object):
    def isNumber(self, s):
        """
        :type s: str
        :rtype: bool
        """
        numbers = '0123456789'
        signs = '+-'
        dot = '.'
        exp = 'e'
        valid = signs+numbers+dot+exp
        s = s.strip()
        if exp in s:
            s = s.split(exp)
        else:
            s = [s]

        if len(s)>2:
            return False
        elif len(s)==2:
            if s[-1]=='':
                return False
            if len(s[-1])==1 and s[-1][0] not in numbers:
                return False
            if s[-1][0] not in numbers+signs:
                return False
            for i in range(1, len(s[-1])):
                if s[-1][i] not in numbers:
                    return False

        s1 = list(s[0])
        if not s1:
            return False
        if len(s1)==1 and s1[0] not in numbers:
            return False
        if s1[0] in signs and s1[1] in signs:
            return False
        if s1.count('.')>1:
            return False
        if s1[-1]=='.' and s1[-2] not in numbers:
            return False
        for i in range(len(s1)-1):
            if s1[i] not in valid:
                return False
            if s1[i]==dot and s1[i+1] not in numbers:
                return False
            if s1[i] in numbers and s1[i+1] not in numbers+dot:
                return False
        return True
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值