C++, one for loop, one conditional, no library methods (6 ms)


  • 0
    P
    class Solution {
    public:
        
        bool IsUpper(char c) {
            return c >= 'A' && c <= 'Z';
        }
    
        bool detectCapitalUse(string word) {
        
            char state = 1 | (IsUpper(word[0]) << 1);
        
            for (int i = 1; i < word.size(); i++) {
                state = state & (IsUpper(word[i]) + 1);
                if (state == 0) return false;
            }
    
            return true;
        }
    };
    

    Using a 4 state Finite State Machine.

    This line sets the initial state to 1 or to 3 depending on whether the first char is lower or upper
    char state = 1 | (IsUpper(word[0]) << 1);

    State 0 is the state in which there has been improper usage of capitalization.
    State 1 is for a string that is all lower chars.
    State 2 is for a string that is all capitals (USA).
    State 3 is for when the first char is capital.


Log in to reply
 

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