0520. Detect Capital

520. Detect Capital #

Problem #

We define the usage of capitals in a word to be right when one of the following cases holds:

All letters in this word are capitals, like “USA”.

All letters in this word are not capitals, like “leetcode”.

Only the first letter in this word is capital, like “Google”.

Given a string word, return true if the usage of capitals in it is right.

Example 1:

Input: word = "USA"
Output: true

Example 2:

Input: word = "FlaG"
Output: false

Constraints:

  • 1 <= word.length <= 100
  • word consists of lowercase and uppercase English letters.

Problem Summary #

We define the usage of capitals in a word to be correct in the following cases:

All letters are uppercase, such as “USA”. All letters in the word are not uppercase, such as “leetcode”. If the word contains more than one letter, only the first letter is uppercase, such as “Google”.

Given a string word. Return true if the usage of capitals is correct; otherwise, return false.

Solution Approach #

  • Convert word into all lowercase wLower, all uppercase wUpper, and a string wCaptial with the first letter capitalized
  • Check whether word is equal to one of wLower, wUpper, or wCaptial; if so, return true, otherwise return false

Code #


package leetcode

import "strings"

func detectCapitalUse(word string) bool {
	wLower := strings.ToLower(word)
	wUpper := strings.ToUpper(word)
	wCaptial := strings.ToUpper(string(word[0])) + strings.ToLower(string(word[1:]))
	if wCaptial == word || wLower == word || wUpper == word {
		return true
	}
	return false
}


Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文