Java solution O(n) time and O(1) space


  • 0
    M

    It is a very simple solution, counting the characters that are in capital letter.
    If count == 1 and it is the first character, return true.
    if count == 0 return true
    if count == word.length() return true
    else return false;

    public class Solution {
        
        public boolean detectCapitalUse(String word) {
            
            int count = 0;
            
            for (int i = 0; i < word.length(); i++) {
                            
                if (word.charAt(i) == Character.toUpperCase(word.charAt(i))) {
                    count++;
                }
    
            }
            
            char first = word.charAt(0);
            if (count == 1 && first == Character.toUpperCase(first)) {
                return true;
            } else if (count == 0) {
                return true;
            } else if (count == word.length()) {
                return true; 
            }
            
            return false;
                
        }
        
    }
    

Log in to reply
 

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