首页 > 试题广场 >

表示数值的字符串

[编程题]表示数值的字符串
  • 热度指数:64245 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
请实现一个函数用来判断字符串str是否表示数值(包括科学计数法的数字,小数和整数)。

科学计数法的数字(按顺序)可以分成以下几个部分:
1.若干空格
2.一个整数或者小数
3.(可选)一个 'e' 或 'E' ,后面跟着一个整数(可正可负)
4.若干空格

小数(按顺序)可以分成以下几个部分:
1.若干空格
2.(可选)一个符号字符('+' 或 '-')
3. 可能是以下描述格式之一:
3.1 至少一位数字,后面跟着一个点 '.'
3.2 至少一位数字,后面跟着一个点 '.' ,后面再跟着至少一位数字
3.3 一个点 '.' ,后面跟着至少一位数字
4.若干空格

整数(按顺序)可以分成以下几个部分:
1.若干空格
2.(可选)一个符号字符('+''-')
3. 至少一位数字
4.若干空格


例如,字符串["+100","5e2","-123","3.1416","-1E-16"]都表示数值。
但是["12e","1a3.14","1.2.3","+-5","12e+4.3"]都不是数值。

提示:
1.1 <= str.length <= 25
2.str 仅含英文字母(大写和小写),数字(0-9),加号 '+' ,减号 '-' ,空格 ' ' 或者点 '.' 。
3.如果怀疑用例是不是能表示为数值的,可以使用python的print(float(str))去查看
进阶:时间复杂度,空间复杂度

示例1

输入

"123.45e+6"

输出

true
示例2

输入

"1.2.3"

输出

false
示例3

输入

"."

输出

false
示例4

输入

"    .2  "

输出

true
class Solution:
    def isNumeric(self , str ):
        # write code here
        try:
            float(str)
            return True
        except Exception:
            return False

发表于 2022-04-27 18:13:07 回复(0)

python利用异常捕获机制(机智)

class Solution:
    def isNumeric(self , str ):
        # write code here
        try:
            float(str)
            return True
        except:
            return False


发表于 2021-11-05 00:03:23 回复(0)
class Solution:
    def isNumeric(self , str ):
        # write code here
        S = ['+','-','e','E','.']
        S1 = ['+','-']
        S2 = ['e' , 'E']
        if not str:
            return False
        n = len(str)
        if str.isdigit():
            return True
        if n == 1:
            return str.isdigit()
        if str[0] in S1:
            str = str[1:]
        else:
            str = str
        for i in str:
            if i.isdigit()&nbs***bsp;i in S:
                continue
            else:
                return False
        e = str.count('e') + str.count('E')
        Fuhao = str.count('+') + str.count('-')
        Point = str.count('.')
        
        if e > 1&nbs***bsp;Fuhao > 1 &nbs***bsp;Point > 1:
            return False
        if not e and Fuhao:
            return False
        if e == 1:
            index_e = str.find('e') + str.find('E')+1 
            print(index_e)
            index_Fuhao = str.find('+') + str.find('-') + 1
            print("fuhao:",index_Fuhao)
            index_Point = str.find('.')
            index = str.find('e') + str.find('E') + 1
            if index_e == 0&nbs***bsp;index_e == len(str)-1:
                return False
            index_point = str.find('.')
            if (index_point > index_e)&nbs***bsp;(index_point == 0)&nbs***bsp;(index_point == len(str)-1):
                return False
            if Fuhao:
                index_Fuhao = str.find('+') + str.find('-')+1
                if index_Fuhao ==0&nbs***bsp;index_Fuhao == len(str)-1&nbs***bsp;index_Fuhao != index_e+1:
                    return False
        return True

发表于 2021-05-14 14:48:49 回复(0)
class Solution:
    def isNumeric(self , str ):
        # write code here
        try:
            float(str)
        except:
            return False
        return True
发表于 2021-05-08 17:17:16 回复(2)
import re 
class Solution:
    def isNumeric(self , str ):
        # write code here
        return re.search(r'^[+-]?(\d+(\.\d+)?|(\.\d+))([eE][+-]?\d+)?$',str)
正则
最开始构思为为
+-    0-1次
数字  0-n次    #因为这里有个  .1也算数字, 也就是.之前的数字可以有0个
(.(数字0-n次))    0-1次
(eE(+- 0-1次)(数字1-n次)) 0-1次

结果出现了 +号也匹配的情况 
所以考虑到 小数点之前和之后两个匹配不能同时为0个,至少有一个时1个,所以中间变为(\d+(\.\d+)?|(\.\d+)) 
发表于 2021-04-20 21:17:30 回复(0)
比较蠢笨的方法……
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param str string字符串 
# @return bool布尔型
#
class Solution:
    def isNumeric(self , str ):
        # write code here
        res=0 ##0表示错误格式 1 表示正确
        if not set(str).issubset({'0','1','2','3','4','5','6','7','8','9','e','E','-','+','.'}):
            return False
        ##存在E或e的情况
        if str.count('e')!=0&nbs***bsp;str.count('E')!=0:
            ##有e有E
            if str.count('e')!=0 and str.count('E')!=0:
                return False
            ##有e无E
            if str.count('e')==1:
                s=str.split('e')
                ##e的后面是非空的,并且不是小数
                if len(s[1])!=0 and s[1].count('.')==0:
                    if self.standardInt(s[1]):
                        res+=1
                ##e的前面
                if len(s[0])==0:
                    res+=1
                if len(s[0])!=0 and s[0][-1]!='.' and s[0].count('.')<=1:
                    if self.standardInt(s[0]):
                        res+=1
            ##有E无e
            if str.count('E')==1:
                s=str.split('E')
                ##E的后面是非空的,并且不是小数
                if len(s[1])!=0 and s[1].count('.')==0:
                    if self.standardInt(s[1]):
                        res+=1
                ##E的前面
                if len(s[0])==0:
                    res+=1
                if len(s[0])!=0 and s[0][-1]!='.' and s[0].count('.')<=1:
                    if self.standardInt(s[0]):
                        res+=1
            if res==2:
                return True
            else:
                return False
        ##不存在e或E的情况
        else:
            if len(str)==0:
                return False
            if len(str)==1 and str.count('.')==str.count('+')==str.count('-')==0:
                return True
            if len(str)>=2 and str[-1]!='.' and str.count('.')<=1:
                if self.standardInt(str):
                    return True
            
        
                    
    ##不考虑'.'的数值格式
    def standardInt(self,str1):
        if len(str1)==1:
            if str1.count('+')==1&nbs***bsp;str1.count('-')==1:
                return False
            else: return True
        if len(str1)>=2:
            res=0
            if str1.count('-')==str1.count('+')==0:
                res+=1
            if str1.count('-')==1 and str1.count('+')==0 and str1.index('-')==0:
                res+=1
            if str1.count('+')==1 and str1.count('-')==0 and str1.index('+')==0:
                res+=1
        if res==1:
            return True
        else: return False

发表于 2021-04-15 13:24:25 回复(0)
"-.123" 这个测试样例的输出应该是True嘛?
发表于 2021-04-11 01:11:25 回复(0)

Python 正则表达式

顺便继续熟悉下 正则表达式

前言

\d 数字
?0次或者1次
* 0次或多次
+ 1次或多次

问题

有个需要注意的是:
match 是可以匹配“12e”中的“12”,直接返回的话会当作true处理,暂时想不到怎么解决。
就笨方法直接判断下匹配到的内容是不是完整的原字符串

代码

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param str string字符串 
# @return bool布尔型
#
class Solution:
    def isNumeric(self , str ):
        import re
        return re.search(r"[+-]?\d*\.?\d*([eE][+-]?\d+)?", str).group()==str
        # write code here
发表于 2021-03-08 21:50:02 回复(1)

问题信息

上传者:牛客301499号
难度:
9条回答 7893浏览

热门推荐

通过挑战的用户

查看代码