L 417. Valid Number

lintcode test case不全
Code(Language:C++) (Judger:ip-172-31-5-19)
class Solution {
public:
    /**
     * @param s: the string that represents a number
     * @return: whether the string is a valid number
     */
    bool isNumber(string &s) {
        // write your code here
        // 这种类型的题,一定要先确定好不valid的情况。然后,统一一个大的思路框架。最后实现。
        // non valid: 1, 非数字,'.','e'的字符 2,.和e出现1一次以上 3,e出现在开头或结尾 4, e和.不能再一起
        //框架: 把空格都去掉;遍历判断;
        const int size = s.size();
        if(size == 0){
            return false; 
        }
        
        // 去空格
        int len = 0; 
        for(int j = 0; j < size; j++){
            if(s[j] != ' '){
                s[len++] = s[j]; 
            }
        }
        //空字符
        if(len == 0){
            return false; 
        }
        // 单独 . 和 e的情况
        if(len == 1){
            if(s[0] == '.' || s[0] == 'e'){
                return false; 
            }
        }
        //判断开头 +,-号
        int i = 0; 
        if(s[0] == '-' || s[0] == '+'){
            i++; 
        }
        int start = i; 
        int cntDot = 0, cntE = 0; 
        for(; i < len; i++){
            // 其他non valid字符
            if(!(s[i] >= '0' && s[i] <= '9' || s[i] == '.' || s[i] == 'e')){
                return false; 
            }
            //多个.
            if(s[i] == '.'){
                if(i > start && s[i - 1] == 'e'){
                    return false; 
                }
                cntDot++;
                if(cntDot > 1){
                    return false; 
                }
            }
            //多个e
            if(s[i] == 'e'){
                if(i > start && s[i - 1] == '.'){
                    return false; 
                }
                cntE++;
                if(cntE > 1){
                    return false; 
                }
            }
        }
        //e出现在开头或结尾。
        if(s[0] == 'e' || s[len - 1] == 'e'){
            return false;
        }
        return true; 
    }
};

Comments

Popular posts from this blog

算法的比较