Detect Capital

 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:

  1. All letters in this word are capitals, like "USA".
  2. All letters in this word are not capitals, like "leetcode".
  3. Only the first letter in this word is capital, like "Google".
Otherwise, we define that this word doesn't use capitals in a right way.

 

Example 1:

Input: "USA"
Output: True

 

Example 2:

Input: "FlaG"
Output: False

 

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.

  class Solution {

    public boolean detectCapitalUse(String word) {

        int length = word.length(), i, upCount=0, flag=0, lowCount = 0;

        for(i=0;i<length;i++){

            if(Character.isUpperCase(word.charAt(i))){

                if(i == 0) flag =1 ;

                upCount++;

            }

            else

                lowCount++;

        }

        if((upCount == length) || (flag == 1 && lowCount == length-1) || (lowCount == length) )

            return true;

        else 

            return false;

    }

}

Try it on Leetcode

The three points which given above in explanation need to be considered for solving in more easier way. Here, we are using upCount for counting upper case and lowCount for counting lower case. Flag is used to identify if uppercase is found in 0th position.

Iterate all characters as per above explanation.

1) a)If upCount is equal to string length, return true. (eg., INDIA)

  b) If Flag equal to 1 and lowcount equal to string length -1, return true. (eg., Fellow)

  c) If lowCount equal to string length, return true (eg., programmer)

2) Else, return false.

Related Post:

Click here for April month challenges with solution and explanation

Click Follow button to receive latest updates from us instantly.

Please let us know about your views in comment section.

Like us? Help us to grow...

Help Others, Please Share..!!!!

                                                     ..Happy Coding...

Comments

Popular posts from this blog

Balanced Binary Tree

First Unique Character in a String

Majority Element

Smallest Range II