Java solution O(N) time, O(1) space complexity


  • 0
    V
    public class Solution {
        public boolean detectCapitalUse(String word) {
            char[] ch = word.toCharArray();
            int len = ch.length;
            int i = 0;
            int u_count = 1; //uppercase count
            int l_count = 1; // lowercase count
            
            if(Character.isUpperCase(ch[i++])) { //1st char is uppercase
                while(i < len && Character.isUpperCase(ch[i])) {
                    u_count++;
                    i++;
                }
                while(i < len && !Character.isUpperCase(ch[i])) {
                    l_count++;
                    i++;
                }
                if(u_count == len) return true;
                if(l_count == len) return true;
            } else { // lowercase
                while(i < len && !Character.isUpperCase(ch[i++])) {
                    l_count++;
                }
                if(l_count == len) return true;
            }
            return false;
        }
    }

Log in to reply
 

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