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.
A very simple problem, slag as I can only be violent solution:
1.brutal force/command-type programming
1 Public classSolution {2 Public BooleanDetectcapitaluse (String word) {3 Char[] Value =Word.tochararray ();4 if(value.length = = 1 | | word = =NULL) {5 return true;6 }7 BooleanSECISUC =false;8 if(Character.islowercase (value[0])) {9 for(intI=1; i<value.length; i++) {Ten if(Character.isuppercase (Value[i])) { One return false; A } - } -}Else { theSECISUC = Character.isuppercase (value[1])?true:false; - if(SECISUC) { - for(inti=2; i<value.length; i++) { - if(Character.islowercase (Value[i])) { + return false; - } + } A}Else { at for(inti=2; i<value.length; i++) { - if(Character.isuppercase (Value[i])) { - return false; - } - } - } in } - return true; to } +}
2. Brute Force solution upgrade version
1 public class solution {2 publicly Boolean detectcapitaluse (String word) {3 int cnt = 0; 4 for (char C:word.tochararray ()) if (' Z '-C >= 0) cnt++; 5 return ((cnt==0 | | cnt==word.length ()) | | (cnt==1 && ' Z '-word.charat (0) >=0 }7}
3. Declarative programming
1 Public BooleanDetectcapitaluse (String word) {2 if(Word.length () < 2)return true;3 if(Word.touppercase (). Equals (word))return true;4 if(Word.substring (1). toLowerCase (). Equals (word.substring (1)))return true;5 return false;6}
4.RegEx
1 Public Boolean Detectcapitaluse (String word) {2 return word.matches ("[a-z]+|[ a-z]+| [A-z] [a-z]+ "); 3 }
String (1)--detect capital