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

表示数值的字符串

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; 
    }
};

全部评论

相关推荐

Aaso:挺好的,早挂早超生
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务