Given a word, you need to determine whether the uppercase word is used correctly.
We define that the use of uppercase words is correct in the following cases:
- All letters are in uppercase, such as "USA ".
- All letters in a word are not in uppercase, such as "leetcode ".
- If a word contains more than one letter, only the first letter is capitalized, such as "google ".
Otherwise, we define that this word does not use uppercase letters correctly.
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.
This question is relatively simple. The first idea is to make three judgments. Whether all characters are in lowercase, whether all characters are in uppercase, whether the first character is in uppercase, and other characters in lowercase.
The Code is as follows:
1 class Solution { 2 public boolean detectCapitalUse(String word) { 3 if (word.equals(word.toLowerCase()) || word.equals(word.toUpperCase())) 4 return true; 5 else if (‘A‘ <= word.charAt(0) && word.charAt(0) <= ‘Z‘) { 6 String tmp = word.substring(1); 7 if (tmp.equals(tmp.toLowerCase())) 8 return true; 9 else10 return false;11 }12 return false;13 }14 }
However, the algorithm execution speed is very slow, and only the 10% player XD is defeated. Because the characters in this string are traversed multiple times. Then I was wondering why I didn't need to traverse it all at once? Because all are uppercase and lowercase, and the first character is uppercase, it can be determined in a traversal. First, set the results to true in all three cases. Then, if any of the three situations does not meet the requirements, set the situation to false and output the three results or results. This execution speed is very fast. Beat 86% of people.
The Code is as follows:
1 class Solution { 2 public boolean detectCapitalUse(String word) { 3 boolean case1=true,case2=true,case3=true; 4 for(int i=0;i<word.length();i++) 5 { 6 if(‘A‘<=word.charAt(i) && word.charAt(i)<= ‘Z‘) 7 { 8 case2=false; 9 if(i>=1)10 case3=false;11 }12 if(‘a‘<=word.charAt(i) && word.charAt(i)<= ‘z‘)13 {14 case1=false;15 if(i==0)16 case3=false;17 }18 }19 return case1 || case2 || case3;20 }21 }
Finally, let's take a look at the difference between the execution speed of C ++ and Java. Then we changed the code using C ++. The result showed that the execution speed was reduced by 20 ms, this time beat 91% of people. C ++ is the best in the world.
The Code is as follows:
1 class Solution { 2 public: 3 bool detectCapitalUse(string word) { 4 bool case1=true,case2=true,case3=true; 5 for(int i=0;i<word.length();i++) 6 { 7 if(‘A‘<=word[i] && word[i]<= ‘Z‘) 8 { 9 case2=false;10 if(i>=1)11 case3=false;12 }13 if(‘a‘<=word[i] && word[i]<= ‘z‘)14 {15 case1=false;16 if(i==0)17 case3=false;18 }19 }20 return case1 || case2 || case3;21 }22 };
Leetcode checks uppercase letters