Question:
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:
Input: "USA"
Output: True
Input: "FlaG"
Output: False
Solution:
/**
* @param {string} word
* @return {boolean}
*/
var detectCapitalUse = function(word) {
let len = word.length;
if (len === 1) return true;
let first = isCapital(word,0);
let second = isCapital(word,1);
for (let i = 2; i < len; i++) {
// 后面不一致
if (isCapital(word,i) != second ) return false;
}
//首字母大写 或 都是小写
return first || (!first && !second);
};
// 是否大写
var isCapital = function (str, index) {
return str.charAt(index) >= 'A' && str.charAt(index) <='Z';
}
Runtime: 60 ms, faster than 100.00% of JavaScript online submissions for Detect Capital.