Monday, March 9, 2015

Valid Number

Valid Number

 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.




---------------------------------------- thinking -----------------------------------
https://leetcode.com/discuss/24878/very-simple-c-sol-not-a-dfa-sol
First let me talk about some requirements.
  1. There could be unlimited space before and after number.
  2. There could be one '+' or '-' before number.
  3. (left).(right) The expression before or after dot could be null, but not both.
  4. (left)e(+/-)(right)
    (1) The expression before e could be a float number.
    (2) The right expression must be a positive integer.
    (3) Both left and right expression couldn't be null.
    (4) There could be a '+' or '-' after e.
------------------------------------------- codes --------------------------------------------
class Solution {
public:
    bool isNumber(string s) {
        int ind = 0;
        skipSpace(s, ind);
        skipSign(s, ind);
        if (!isNumber(s, ind)) {
            return false;
        }
        if (ind < s.size() && (s[ind] == 'e'|| s[ind] == 'E')) {
            ind++;
            skipSign(s, ind);
            if (!isInteger(s, ind)) {
                return false;
            }
        }
        skipSpace(s, ind);
        if (ind < s.size()) {
            return false;
        } else {
            return true;
        }
    }
    bool skipSpace(string s, int &ind) {
        int len = 0;
        while (ind < s.size() && s[ind] == ' ') {
            ind++;
            len++;
        }
        if (len > 0) {
            return true;
        } else {
            return false;
        }
    }
    bool skipSign(string s, int &ind) {
        if (ind < s.size() && (s[ind] == '+' || s[ind] == '-')) {
            ind++;
            return true;
        } else {
            return false;
        }
    }
    bool isInteger(string s, int &ind) {
        int len = 0;
        while (ind < s.size() && (s[ind] >= '0' && s[ind] <= '9')) {
            ind++;
            len++;
        }
        if (len > 0) {
            return true;
        } else {
            return false;
        }
    }
    bool isNumber(string s, int &ind) {
        int len = 0;
        while (ind < s.size() && (s[ind] >= '0' && s[ind] <= '9')) {
            ind++;
            len++;
        }
        if (len>0 && ind == s.size()) {
            return true;
        }
        if (s[ind] == '.') {
            ind++;
        } 
        while (ind < s.size() && (s[ind] >= '0' && s[ind] <= '9')) {
            ind++;
            len++;
        }
        if (len > 0) {
            return true;
        } else {
            return false;
        }
    }
};

No comments:

Post a Comment