Java Solution - O(n) and constant space


  • 0
    V

    Step 1: Count the number of capital letters in the word
    Step 2: Return true if one of the following is satisfied -
    (i) If count equals word's length (All caps word)
    (ii) If count is one and first letter is in caps (Eg: Leetcode)
    (iii) If count is 0 (All lowercase word)

     public boolean detectCapitalUse(String word) {
            int n = word.length(), caps = 0;
            for(int i=0; i<n; i++) 
                if('Z' - word.charAt(i) >= 0)       caps++;
            return caps == n || caps == 0 || (caps == 1 && ('Z' - word.charAt(0) >= 0));
        }
    

Log in to reply
 

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