Beat 70% - simple for loop


  • 0
    S
    public class Solution {
        public boolean detectCapitalUse(String word) {
            if (word.length() == 0) return true;
            
            boolean isAllCaps = false;
            
            for (int i = word.length() - 1; i > 0; --i) {
                char curr = word.charAt(i);
                char prev = word.charAt(i-1);
                
                isAllCaps = isCapital(curr);
                if (isCapital(curr) != isCapital(prev) && i > 1) return false;
            }
            
            return isAllCaps ? isCapital(word.charAt(0)) : true;
        }
        
        public boolean isCapital(char c) {
            return c >= 'A' && c <= 'Z';
        }
    
    }
    

  • 0
    N

    I love the readability of this. Nice job.


Log in to reply
 

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