Detect Capital – Leetcode #520

This problem is from Leetcode – Detect Capital. Problem statement in short is as below:

Return true if a word is all uppercase, all lowercase, or only the first letter is uppercase; otherwise, false.

Solution

To determine if the usage of capitals in a given word is correct according to the specified rules, we can implement a function that checks the following conditions:

  1. All letters are uppercase.
  2. All letters are lowercase.
  3. Only the first letter is uppercase, and the rest are lowercase.

See the code sample below:

public boolean detectCapitalUse(String word) {

		Boolean isCapital = false;

		// check if all chars are lowercase
		if(word.equals(word.toLowerCase())) {

			return true;
		}

		// check if all chars are uppercase
		else if(word.equals(word.toUpperCase())) {

			return true;
		}

		// check if first char is uppercase and rest are lowercase
		if(Character.isUpperCase(word.charAt(0)))  {

			String str = word.substring(1, word.length());

			if(str.equals(str.toLowerCase())) {

				return true;
			}
		}


		return isCapital;
	}

You can checkout the code from Github here: Detect Capital – First Approach. See the performance of this approach below:

PERFORMANCE ANALYSIS

RUNTIME2 ms | Beats 38.90 %
MEMORY41.28 MB | Beats 99.07 %
TIME COMPLEXITYO (N)

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top