Friday, November 1, 2013

Valid Number [Leetcode]

Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

Solution: see the following code for details.
class Solution {
public:
    string clearSpace(const char *s){
        //remove leading and trailing spaces of non-empty string
        string ret;
        int start=0;
        while(start<strlen(s) && isspace(s[start]))
            start++;
        if(start==strlen(s))
            return ret;
        int end=strlen(s)-1;
        while(isspace(s[end])) 
            end--;
        for(int i=start; i<=end; ++i)
            ret+=s[i];
        return ret;
    }
    bool isNumber(const char *s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(s==NULL || *s=='\0')
            return false;
        string r = clearSpace(s);
        if(r.empty())
            return false;

        int start=0;
        if(r[0]=='+' || r[0]=='-')
            start++;
        //starting at 'start', each of e/E, dot, and +/- can occur at most once
        int eIndex = -1, dotIndex = -1, signIndex = -1;
        for(int i=start; i<r.size(); ++i){
            if((r[i]=='e' || r[i]=='E') && eIndex==-1)
                eIndex=i;
            else if((r[i]=='+' || r[i]=='-') && signIndex==-1)
                    signIndex=i;
            else if(r[i]=='.' && dotIndex==-1)
                dotIndex=i;
            else if(!isdigit(r[i]))
                return false;
        }
        //check the positons of e/E, dot, and +/-
        //Specifically, dot must be in the front of e/E, and e/E must be in the RIGHT front of +/-
        //+/- must have a following digit; e/E cannot be in the first and last position;
        //dot is not the unique char of string, and if dot is the first char, the next char cannot be e/E.
        if(signIndex!=-1) //found +/-
            if(eIndex==-1 || signIndex!=eIndex+1 || signIndex==r.size()-1 || !isdigit(r[signIndex+1]))
                return false;
        if(eIndex!=-1) //found e
            if(eIndex==start || eIndex==r.size()-1 || eIndex<dotIndex)
                return false;
        if(dotIndex!=-1) //found dot
            if(dotIndex==start && (dotIndex==r.size()-1 || eIndex!=-1&& dotIndex==eIndex-1))
                return false;
        return true;
    }
};

No comments:

Post a Comment