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:
- 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".
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;
}
}
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.
Comments
Post a Comment