Java solution #interview


  • 0

    This is not the perfect solution given there are other concise and elegant ones. However, this is the one I would likely come up with in 2 minutes without too many thoughts during an interview.

    I'll improve its brevity if I have more time, but the current logic is clear enough.

    public class Solution {
        public boolean detectCapitalUse(String word) {
            boolean firstCharUpperCase = Character.isUpperCase(word.charAt(0));
            boolean mode1 = firstCharUpperCase; // USA
            boolean mode2 = !firstCharUpperCase; // leetcode
            boolean mode3 = firstCharUpperCase; // Google
            
            for (int i=1; i<word.length(); ++i) {
                boolean isUpperCase = Character.isUpperCase(word.charAt(i));
                
                if (mode1 && !isUpperCase) {
                    mode1 = false;
                }
                
                if (mode2 && isUpperCase) {
                    mode2 = false;
                }
                
                if (mode3 && isUpperCase) {
                    mode3 = false;
                }
            }
            
            return mode1 | mode2 | mode3;
        }
    }
    

Log in to reply
 

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