leetcode Daily Challenge on August 1st, 2020.
Difficulty : Easy
Related Topics : String
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.
Input: "USA" Output: True
Input: "FlaG" Output: False
- The input will be a non-empty word consisting of uppercase and lowercase latin letters.
- mine
- Java
Runtime: 1 ms, faster than 99.86%, Memory Usage: 39.2 MB, less than 10.00% of Java online submissions
// O(N)time // O(N)space public boolean detectCapitalUse(String word) { char[] arr = word.toCharArray(); int count = 0; for(char c : arr){ if(c <= 'Z'){ count++; } } if(count == arr.length || count == 0) return true; if(count == 1 && arr[0] <= 'Z') return true; return false; }
- Java
- the most votes
Runtime: 2 ms, faster than 51.16%, Memory Usage: 39.5 MB, less than 5.71% of Java online submissions
// O(N)time // O(N)space public boolean detectCapitalUse(String word) { int cnt = 0; for(char c: word.toCharArray()) if('Z' - c >= 0) cnt++; return ((cnt==0 || cnt==word.length()) || (cnt==1 && 'Z' - word.charAt(0)>=0)); }