My solution using simple state machine


  • 0
    E
    class Solution {
    public:
        bool detectCapitalUse(string word) {
            // three status
            enum { ALL_CAP = 1, ALL_UNCAP, FIRST_CAP };
            int status = 0;
            // determine initial status
            if ('a' <= word[0] && word[0] <= 'z')
                status = ALL_UNCAP;
            else 
                status = FIRST_CAP;
                
            for (int i = 1; i < word.size(); i++) {
                if ('a' <= word[i] && word[i] <= 'z') {
                    switch (status) {
                        case ALL_CAP:
                            return false;
                        case ALL_UNCAP:
                            continue;
                        case FIRST_CAP:
                            continue;
                    }
                } else {
                    switch (status) {
                        case ALL_CAP:
                            continue;
                        case ALL_UNCAP:
                            return false;
                        case FIRST_CAP:
                            if (i == 1) {
                                status = ALL_CAP;
                                continue;
                            } else
                                return false;
                    }
                }
            }
            return true;
        }
    };
    

Log in to reply
 

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