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;
            }
            if(small){
                //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.

Comments

Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

First Unique Character in a String Java - The Coding Shala

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

Add two numbers in Scala - The Coding Shala