A solution very easy to understand


  • 0
    L
    class Solution {
    public:
        bool isNumber(string s) {
            // mode +0.0e+0
            //      1234567
            int start = s.find_first_not_of(' ');
            if (start == string::npos)
                return false;
            bool integral = false;
            int end = s.find_last_not_of(' ');
            s = s.substr(start, end - start + 1);
            int mode = 0;
            for (char c: s) {
                if (isdigit(c)) {
                    if (mode <= 2)
                        mode = 2;
                    else if (mode <= 4)
                        mode = 4;
                    else if (mode <= 7)
                        mode = 7;
                    continue;
                }
                switch (c) {
                    case '+':
                    case '-':
                        if (mode == 0)
                            mode = 1;
                        else if (mode == 5)
                            mode = 6;
                        else
                            return false;
                        break;
                    case '.':
                        if (mode == 2)
                            integral = true;
                        if (mode <= 2)
                            mode = 3;
                        else
                            return false;
                        break;
                    case 'e':
                        if (mode == 2 || mode == 4 || mode == 3 && integral)
                            mode = 5;
                        else
                            return false;
                        break;
                    default:
                        return false;
                }
            }
            return (mode == 2 || (mode == 3 && integral) || mode == 4 || mode == 7);
    

    Basic idea is to use pattern mode to match.
    integral is used to differentiate .e-1(invalid) vs 1.e-1(valid)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.