Back to Leetcode Go

520. Detect Capital

website/content.en/ChapterFour/0500~0599/0520.Detect-Capital.md

1.7.971.6 KB
Original Source

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

go

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
}