题解 | #表示数值的字符串#

表示数值的字符串

https://www.nowcoder.com/practice/e69148f8528c4039ad89bb2546fd4ff8

#include <type_traits>
class Solution {
public:
    bool isNumeric(string str) {
        for (int i = 0; i < str.size(); i++){
            if (str[i] == 'e' || str[i] == 'E')
                return science(str, i);
        }
        for (auto s : str){
            if (s == '.')
                return xiaoshu(str);
        }
        return zhengshu(str);
    }
    bool science(string str, int sci_index){
        string pre = str.substr(0 , sci_index);
        string post = str.substr(sci_index + 1 , str.size() - sci_index - 1);
        return (zhengshu(pre) || xiaoshu(pre)) && zhengshu(post);
    }
    bool zhengshu(string str){
        bool symbol_index = false;
        bool num_index = false;
        for (auto s : str){
            if (s == '+' || s == '-'){
                if (symbol_index || num_index)
                    return false;
                else 
                    symbol_index = true;
            }
            else{
                if (s >= '0' && s <= '9')
                    num_index = true;
                else  if (s != ' ')
                    return false;                    
            }
        }
        return num_index;
    }
    bool xiaoshu(string str){
        int num = 0;
        for (auto s : str){
            if (s == '.')
                num++;
        }
        if (num != 1)
            return false;
        int k = 0;
        while (str[k] != '.'){
            k++;
        }
        bool num_index1 = false;
        bool num_index2 = false;
        bool symbol_index = false;
        for (int i = 0; i < k; i++){
            if (str[i] == '+' || str[i] == '-'){
                if (symbol_index || num_index1)
                    return false;
                else 
                    symbol_index = true;
            }
            else{
                if (str[i] >= '0' && str[i] <= '9')
                    num_index1 = true;
                else  if (str[i] != ' ')
                    return false;   
            }
        }
        for (int i = k + 1; i < str.size(); i++){
            if (str[i] >= '0' && str[i] <= '9')
                num_index2 = true;
            else  if (str[i] != ' ')
                return false;   
        }
        return num_index1 || num_index2; 
    }
};

全部评论

相关推荐

10-29 22:30
吉林大学 Java
同专业学长学姐,去互联网大厂的起薪&nbsp;15k+,去国企&nbsp;IT&nbsp;岗的也有&nbsp;12k+,就连去中小厂的都基本&nbsp;13k&nbsp;起步😤&nbsp;我投的传统行业技术岗,拼死拼活拿到&nbsp;1Woffer,本来还挺开心,结果逛了圈牛客直接破防,同是校招生,行业差距怎么就这么大啊!
喵喵喵6_6:应该哪里不对吧,大厂都是20k以上的,10k那种对于985本的学生基本就是点击一下过了笔试就送的,我前两天刚拿了一个11k,笔试完第2天就打电话了,非科班。坏消息是c++岗开这么低真是刷新认知了
校招生月薪1W算什么水平
点赞 评论 收藏
分享
10-22 19:44
门头沟学院 Java
面了100年面试不知...:那我得去剪个头
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务