Title Description:
Given A word, you need to judge whether the usage of capitals in it are right or not.
We define the usage of capitals in a word to being right when one of the following cases holds:
- All letters in this word is capitals, like "USA".
- All letters in this word is not capitals, like "Leetcode".
- Only the first letter of this word was capital if it had more than one letter, like "Google".
Otherwise, we define that this word doesn ' t use capitals in a right-to-do.
Example 1:
Input: "USA" output:true
Example 2:
Input: "FlaG" Output:false
Note:the input is a non-empty word consisting of uppercase and lowercase Latin letters.
to complete the function:
BOOL Detectcapitaluse (string word)
Description:
1, this problem is not difficult, in fact, is to judge the form of the word in conformity with the law. The topic is given several criteria for judging:
If all letters are uppercase, then it is legal. such as USA
If all letters are lowercase, then it is legal. such as Leetcode
If the word is more than one character, and the first letter is capitalized, the remaining letters are lowercase, then it is legal. such as Google
2, after understanding the conditions, we write the judgment statement.
The code is as follows:
BOOLDetectcapitaluse (stringword) { BOOLflag=1; if(word.size () = =1)//Boundary conditionreturn true; if(Islower (word[1])//The second letter is lowercase and must then be lowercase { for(intI=2; I<word.size (); i++) { if(Isupper (Word[i])) {flag=0; Break; } } if(flag==0) return false; Else return true;//Whether the first letter case is legal}Else { for(intI=2; I<word.size (); i++)//The second letter is capitalized and must then be capitalized {if(Islower (Word[i])) {flag=0; Break; } } if(flag==0) return false; if(Isupper (word[0])//first letter capitalized, legalreturn true; Else return false;//first letter lowercase, not valid}}
The above code includes all the judging conditions, measured 15ms,beats 57.47% of CPP submissions.
3, in the discussion area to see someone using a string matching method to do this problem, only write a line of code, but the measured effect is very slow ...
Leetcode-520-detect Capital