A Different Approach Exploiting word[1,...,n-1]


  • 0
    P

    Let's denote uppercase letter with U, lowercase with l.

    Despite the word might be Ulllll, UUUUU or lllll, a nice property is that the range [1,..., n-1] should have the same upper/lower case form. My solution based on the observation in 2 steps:

    1. check whether same form in [1,...,n-1] holds true;
    2. check whether it's invalid lUUUU with word[0] and word[1], and return.

    Code below:

    bool detectCapitalUse(string word) {
            if (word.length() < 2) {
                return true;
            }
            
            /* range [1, ..., n - 1] must have the same upper/lower case */
            for (int i = 2; i < word.length(); i++) {
                if (isupper (word[1]) != isupper(word[i])) {
                    return false;
                }
            }
            
            /***
             * word[0] : word[1,2,3,...,n-1]
             * UPPER : lower
             * UPPER : UPPER
             * lower : Upper, invalid case
             * lower : lower
             */
             return !(islower(word[0]) && isupper(word[1]));
        }
    

Log in to reply
 

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