520. Detect Capital

Posted phdeblog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了520. Detect Capital相关的知识,希望对你有一定的参考价值。

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"
Output: True

Example 2:

Input: "FlaG"
Output: False

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.

解题:这个题目是挺简单的,主要是要读懂题目。一开始读第二句话时“not captitals”以为举的是反例呢,其实标1,2,3的都是条件,也是正解。detect,是“侦查”、"发现"的意思,而这个 captial 除了”省会"还有大写字母的意思。所以依然还是感觉这个题目不好。。。QAQ

把题目中的条件翻译一下:

(1)都是大写字母的,满足条件

(2)都是小写字母的,满足条件

(3)开头大写,后面小写的,也满足条件

这样代码就出来了:

 1 class Solution {
 2     
 3     public boolean detectCapitalUse(String word) {
 4         //都是大写,或者都是小写
 5         if(word.equals(word.toUpperCase()) || word.equals(word.toLowerCase()))
 6             return true;
 7         //开头字母大写,后面小写
 8         if(Character.isUpperCase(word.charAt(0))){
 9              String str = word.substring(1);
10             if(str.equals(str.toLowerCase()))
11                 return true;
12         }
13            return false;
14     }
15 }

 

以上是关于520. Detect Capital的主要内容,如果未能解决你的问题,请参考以下文章

520. Detect Capital

LeetCode 520. Detect Capital

Leetcode 520. Detect Capital

LeetCode - 520. Detect Capital

520. Detect Capital

leetcode-520-Detect Capital