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

表示数值的字符串

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

直接通过规则判断即可,一层循环,时间复杂度为O(n)。

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param str string字符串 
     * @return bool布尔型
     */
    bool isNumeric(string str) {
        // write code here
        int idx;
        for(idx=0;idx<str.length();idx++){
            if(str[idx]==' ') continue;
            else break;
        }
        int e_counter = 0;
        int dot_counter = 0;
        int dot_pos = -1;
        int e_pos = -1;
        int sign_counter = 0;
        bool start_blank = false;
        int first_num_pos = -1;
        int last_num_pos = -1;
        bool meet_num = false;
        for(int i=idx;i<str.length();i++){
            if(str[i]==' '&&!start_blank) start_blank = true;
            if(start_blank&&str[i]!=' ') return false;
            if((str[i]>='A'&&str[i]<='Z')||str[i]>='a'&&str[i]<='z'){
                if(str[i]=='e'||str[i]=='E'){
                    e_counter++;
                    e_pos = i;
                    if(e_counter>1) return false;
                }
                else {
                    return false;
                }
            }
            if(str[i]=='+'||str[i]=='-'){
                if(i-1>=0){
                    if(str[i-1]==' '||str[i-1]=='e'||str[i-1]=='E'){
                        sign_counter++;
                        if(sign_counter>2) return false;
                        continue;
                    }
                    else {
                        return false;
                    }
                }
                else{
                    sign_counter++;
                    if(sign_counter>2) return false;
                }
            }
            if(str[i]=='.'){
                if((i-1>=0&&str[i-1]>='0'&&str[i-1]<='9')||(i+1<str.length()&&str[i+1]>='0'&&str[i+1]<='9')){
                    dot_counter++;
                    dot_pos=i;
                    if(dot_counter>1) return false;
                    continue;
                }
                else {
                    return false;
                }
            }
            if(str[i]>='0'&&str[i]<='9'){
                if(meet_num){
                    last_num_pos = i;
                }
                else {
                    first_num_pos = i;
                    last_num_pos = i;
                    meet_num = true;
                }
            }
        }
        if(!meet_num) return false;
        
        if(e_pos!=-1&&e_pos>last_num_pos) return false;
        if(e_pos!=-1&&dot_pos!=-1&&dot_pos> e_pos) return false;
        if(e_pos!=-1&&first_num_pos>e_pos) return false;

        return true;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务