头像

带翅膀的猫

时光荏苒,我们一直都在

《LeetCode刷题(Easy Rank):520. Detect Capital》

 3周前  •   LeetCode  •     •   7  •   0

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

Example 2:

示例Input: "FlaG"
Output: False

Solution:

JAVAclass Solution {
    public boolean detectCapitalUse(String word) {
        boolean flag=false;
        if(word.length()<1){
            return false;
        }
        for(int i=1;i<word.length();i++){
            if((word.charAt(i)>='a'&&word.charAt(i)<='z')&&(word.charAt(i-1)>='A'&&word.charAt(i-1)<='Z')&&i!=1){//第i个字符是小写,但是它的前一个字符是大写,并且前一个字符不是首字符,这不符合规则,返回false
                return false;
            }
            if((word.charAt(i-1)>='a'&&word.charAt(i-1)<='z')&&(word.charAt(i)>='A'&&word.charAt(i)<='Z')){//第i个字符是大写,但是它的前一个是小写,这不符合规则,返回false
                return false;
            }
        }
        return true;
    }
}

更简洁的方法:

遍历整个字符串,是以numUpper记录大写字符个数,如果只有一个大写字符,那么这个字符必须在首字符才合法,否则不合法;如果有大于1个大写字符,只有所有都是大写字符才合格,否则不合格;如果没有大写字符,那显然是合格的。

JAVAclass Solution {
    public boolean detectCapitalUse(String word) {
        int numUpper = 0;
        for (int i=0;i<word.length();i++)
            if (Character.isUpperCase(word.charAt(i))) numUpper++;
        if (numUpper == 1) return Character.isUpperCase(word.charAt(0));
        return numUpper == 0 || numUpper == word.length();
    }
}

 

 

上一篇:
下一篇:

 评论


 已有0条评论

    还没有任何评论,你来说两句吧!