表示数值的字符串,剑指经典解法!!!

表示数值的字符串

http://www.nowcoder.com/questionTerminal/e69148f8528c4039ad89bb2546fd4ff8

/*
   参考剑指offer,改动了一些小部分。
    数值可以表示为 A[.[B]]e|E[C]
    其中A 和C 可以带有正负号,B不能带有符号
    A可以没有,B也可以没有,不过在'.'的情况下
    在e|E ,B是必须有的,所以这就是在判断str[index]=='.' 和str[index]=='e'||             
    str[index]=='E'时是使用不同运算符的原因。
    然后分解成两个函数小函数我觉得可读性强一点,毕竟代码给人看的,想看细节的同学
    请移步剑指offer官方书籍。
*/
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param str string字符串 
     * @return bool布尔型
     */
    bool isNumeric(string str) {
        // write code here
        if(str.empty()) return false;
        size_t index=0;
        bool numeric=scanInteger(str,index);
        if(str[index]=='.'){
            ++index;
            bool hasNumbers=scanUnsignedInteger(str,index);
            numeric=hasNumbers || numeric;
        }
        if(str[index]=='e'|| str[index]=='E'){
            ++index;
            numeric=numeric && scanInteger(str,index);
        }
        return numeric && (index==str.size());

    }
    bool scanInteger(string& str,size_t& index){
        if(str[index]=='+'||str[index]=='-')
            ++index;
        return scanUnsignedInteger(str,index);
    }
    bool scanUnsignedInteger(string& str,size_t& index){
        size_t begin=index;
        while(str[index]!='\0' && str[index]>='0'&& str[index]<='9')
            ++index;
        return index>begin;
    }
};
全部评论
前后有若干空格的情况貌似没有考虑到
点赞 回复 分享
发布于 2021-10-19 22:48
确实是。当初这个题按照书上来是没有这个限制条件的,所以就没有考虑前导空格。后面牛客可能补充更新了。
点赞 回复 分享
发布于 2021-10-20 09:01
很强,思路很清晰,加上前后空格去除就好了
点赞 回复 分享
发布于 2022-03-28 22:30

相关推荐

点赞 评论 收藏
分享
西松屋:说明原部门有机会把
点赞 评论 收藏
分享
评论
8
1
分享

创作者周榜

更多
牛客网
牛客企业服务