Detect Capital LeetCode Solution - The Coding Shala
Home >> LeetCode >> Detect Capital
Other Posts You May Like
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; } }
- LeetCode - To Lower Case
- LeetCode - Destination City
- LeetCode - Word Subsets
- LeetCode - Shifting Letters
- LeetCode - Valid Boomerang
Comments
Post a Comment