题目:
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 if it has more than one letter, like "Google".
Otherwise, we define that this word doesn't use capitals in a right way.
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.
链接:https://leetcode.com/problems/detect-capital/#/description
3/31/2017
13%, 51ms
用了自带的函数,如果用Python连第三种情况都可以直接title()来比较
1 public class Solution { 2 public boolean detectCapitalUse(String word) { 3 if (word.equals(word.toUpperCase()) || word.equals(word.toLowerCase())) return true; 4 if (word.charAt(0) >= 'A' && word.charAt(0) <= 'Z' && word.substring(1, word.length()).equals(word.substring(1, word.length()).toLowerCase())) return true; 5 return false; 6 } 7 }
1 def detectCapitalUse(self, word): 2 return word.isupper() or word.islower() or word.istitle()
别人的regex方法,但是需要53ms
1 public boolean detectCapitalUse(String word) { 2 return word.matches("[A-Z]+|[a-z]+|[A-Z][a-z]+"); 3 }
或者,我更喜欢这个
1 public boolean detectCapitalUse(String word) { 2 return word.matches("[A-Z]*|[A-Z]?[a-z]*"); 3 }
https://discuss.leetcode.com/topic/79930/java-1-liner/3
这个方法也很聪明:ascii码当中,大写在小写之前,只需要29ms
https://discuss.leetcode.com/topic/79912/3-lines
1 public class Solution { 2 public 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)); 6 } 7 }
朴实但是很聪明的解法,比较大写的数量和位置。34ms,注意Character.isUpperCase
https://discuss.leetcode.com/topic/79911/simple-java-solution-o-n-time-o-1-space
1 public boolean detectCapitalUse(String word) { 2 int numUpper = 0; 3 for (int i=0;i<word.length();i++) { 4 if (Character.isUpperCase(word.charAt(i))) numUpper++; 5 } 6 if (numUpper == 1) return Character.isUpperCase(word.charAt(0)); 7 return numUpper == 0 || numUpper == word.length(); 8 }
更多讨论: