Java Solution O(n) with explanation


  • 0
    S

    Explanation:

    A) Count total number lower-case characters and upper-case characters
    B) Check if first character is upper-case
    C) If first character is lower-case then all remaining characters must be lowercase. (lower-case character count must be equal to length of array EXCLUDING first character)
    D) If first character is upper-case then all remaining character must be EITHER upper-case OR lower-case (either lower-case count or upper-case character count must be equal to length of array EXCLUDING first character)

    class Solution {
        public boolean detectCapitalUse(String word) {
            char[] arr = word.toCharArray();
            int up = 0;
            int lo = 0;
            
            for(int i = 1; i < arr.length; i++) {
                if(Character.isUpperCase(arr[i])) {
                    up++;
                }
                else {
                    lo++;
                }
            }
            
            boolean firstCapital = Character.isUpperCase(arr[0]);
            
            if(firstCapital) {
                return firstCapital && (up == arr.length - 1 || lo == arr.length - 1);
            }
            else {
                return lo == arr.length - 1;
            }
        }
    }
    

Log in to reply
 

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