Detect Capital LeetCode Solution - The Coding Shala

Home >> LeetCode >> Detect Capital

 In this post, we will learn how to solve LeetCode's Detect Capital Problem and will implement its solution in Java.

Detect Capital Problem

Given a word, you need to judge whether the usage of capitals in it is right or not. 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".
Otherwise, we define that this word doesn't use capitals in the right way.

Example 1:
Input: "USA"
Output: True

Example 2:
Input: "FlaG"
Output: False

Practice this problem on LeetCode(Click Here).

Detect Capital Java Solution

Approach 1

Check all the conditions.

Java Program: 

class Solution {
    public boolean detectCapitalUse(String word) {
        int flag = 0;
        boolean small = false;
        for(int i=0; i<word.length(); i++) {
            int ascii = (int) word.charAt(i);
            if(i == 0) {
                //check first char as small
                if(ascii > 96) small = true;
                //to check not all the chars are capitals
                if(ascii < 97) return false;
                else flag++;
            } else {
                if(ascii < 97) flag++;
        if(flag == 1 || flag == word.length()) return true;
        return false;

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.


Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala