zoukankan      html  css  js  c++  java
  • [Leetcode]@python 65. Valid Number

    题目链接:https://leetcode.com/problems/valid-number/


     题目大意:给定一个字符串,判断是否是数字

         如:"0" => true
           " 0.1 " => true
             "abc" => false
           "1 a" => false
           "2e10" => true


     解题思路:先将两端的空格去掉,判断开始是否数字,如果不是直接返回False,然后判断是否遇到'.'和‘e',然后判断'e'以后是否有’+‘,’-‘和’.'。


     代码(python):

    class Solution(object):
        def isNumber(self, s):
            """
            :type s: str
            :rtype: bool
            """
            begin, last = 0, len(s) - 1
            # 将字符串前后的空格去掉
            while begin <= last and s[begin] == ' ':
                begin += 1
            while begin <= last and s[last] == ' ':
                last -= 1
    
            # 数字前为正号或者负号的情况,首位后移
            if begin < last and (s[begin] == '+' or s[begin] == '-'):
                begin += 1
            num, dot, exp = False, False, False
    
            while begin <= last:
                # 该字符为数字
                if s[begin] >= '0' and s[begin] <= '9':
                    num = True
                # 若首位为"."则返回false,否则标记为小数
                elif s[begin] == '.':
                    if dot or exp:
                        return False
                    dot = True
                # 若首位为"e"或"E",则返回false,否则标记为科学计数
                elif s[begin] == 'e' or s[begin] == 'E':
                    if exp or not num:
                        return False
                    exp, num = True, False
                # 若遇到正负号,则判断前一位是否为字符"e"或"E"
                elif s[begin] == '+' or s[begin] == '-':
                    if s[begin - 1] != 'e':
                        return False
                else:
                    return False
                begin += 1
            return num
    View Code

  • 相关阅读:
    防抖节流函数
    富文本编辑器tinymce在vue中的使用
    vue脚手架中检测lodop安装情况
    打印插件LODOP Vue中的使用
    vue打包后刷新页面报错:Unexpected token <
    Bootstrap-table表格插件的使用方法
    jsTree树插件
    Vue监控器watch的全面解析
    Vue计算属性computed的全面解析
    基于JQuery可拖动列表格插件DataTables的踩坑记
  • 原文地址:https://www.cnblogs.com/slurm/p/5110406.html
Copyright © 2011-2022 走看看