Non regexp Java solution


  • 0
    A

    At the first step the problem may seem very easy to implement. However things starts going complicated when you start to think about less lines of codes. Exactly for this problem it is more easy to write straight forward solution. So, there are only 3 options. It is enough to consider each of them separately like in the code below.

    public class Solution {
        public boolean detectCapitalUse(String word) {
            if (word==null || word.isEmpty()) return true;
            return (isUpper(word) || isLower(word) || isNormal(word));
        }
        
        private boolean isUpper(String word) {
            for (int i=0; i<word.length(); i++) {
                if (Character.isLowerCase(word.charAt(i))) {
                    return false;
                }
            }
            return true;
        }
        
        
        private boolean isLower(String word) {
            for (int i=0; i<word.length(); i++) {
                if (Character.isUpperCase(word.charAt(i))) {
                    return false;
                }
            }
            return true;
        }
        
        private boolean isNormal(String word) {
            if (word.length()>1) {
                if (Character.isUpperCase(word.charAt(0))) {
                    for (int i=1; i<word.length(); i++) {
                        if (Character.isUpperCase(word.charAt(i))) {
                            return false;
                        }
                    }
                } else {
                    return false;
                }
            } else {
                return false;
            }
            return true;
        }
    }
    

Log in to reply
 

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