Easy to understand Java Solution with comment


  • 0
    G
    public class Solution {
        public boolean detectCapitalUse(String word) {
            // Use a counter to record the number of upper letters
            int count = 0;
            for (int i = 0; i < word.length(); i++) {
                if (word.charAt(i) <= 'Z') {
                    count++;
                }
            }
            // If 1. all lower letters 2. all upper letters 3. first upper letter only, return true
            if (count == 0 || count == word.length() || count == 1 && word.charAt(0) <= 'Z') {
                return true;
            }
            return false;
        }
    }
    

  • 0
    C

    @getaccepted
    A small suggestion.
    The last 4 lines can be changed to 1 line.

    return (count == 0 || count == word.length() || count == 1 && word.charAt(0) <= 'Z')
    

    This trick is useful when your method returns boolean value through if else statement!


  • 0
    G

    @cuberyao Thanks for your suggestion!


Log in to reply
 

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