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.

Examples

Example 1:

Input: word = "USA"
Output: true

Example 2:

Input: word = "FlaG"
Output: false

Solution

Method 1 - Using Counter

Code

Java
public boolean detectCapitalUse(String word) {
	if (word.length() == 1) {
		return true;
	}
	int caps = 0;
	for (int i = 0; i < word.length(); i++) {
		if (Character.isUpperCase(word.charAt(i))) {
			caps++;
		}
	}

	return caps == word.length() || caps == 0 || (caps == 1 && Character.isUpperCase(word.charAt(0)));
}
Rust
pub fn detect_capital_use(word: String) -> bool {
	let mut caps = 0;
	let word_: Vec<char> = word.chars().collect();
	let n = word.len();
	for i in 0..n {
		if word_[i].is_uppercase() {
			caps += 1;
		}
	}

	return caps == n || caps == 0 || (caps == 1 && word_[0].is_uppercase());
}