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:

  1. All letters in this word are capitals, like “USA”.

  2. All letters in this word are not capitals, like “leetcode”.

  3. 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"
  2. Output: True
  1. Input: "FlaG"
  2. Output: False

Solution:

  1. /**
  2. * @param {string} word
  3. * @return {boolean}
  4. */
  5. var detectCapitalUse = function(word) {
  6. let len = word.length;
  7. if (len === 1) return true;
  8. let first = isCapital(word,0);
  9. let second = isCapital(word,1);
  10. for (let i = 2; i < len; i++) {
  11. // 后面不一致
  12. if (isCapital(word,i) != second ) return false;
  13. }
  14. //首字母大写 或 都是小写
  15. return first || (!first && !second);
  16. };
  17. // 是否大写
  18. var isCapital = function (str, index) {
  19. return str.charAt(index) >= 'A' && str.charAt(index) <='Z';
  20. }

Runtime: 60 ms, faster than 100.00% of JavaScript online submissions for Detect Capital.