520. Detect Capital 的OJ代码笔记

来源:互联网 发布:java方法签名 异常 编辑:程序博客网 时间:2024/05/20 16:43

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.

Subscribe to see which companies asked this question.

Show Tags
通过代码如下:







public class Solution {

    public boolean detectCapitalUse(String word) {
       boolean flag=false;
 int small=0;
 int big=0;
 char[] temp=word.toCharArray();
 System.out.println("word:"+word);
 if(word.length()==1){
 if(temp[0]>='A' && temp[0]<='Z')
 {
 return true;
 }
 }
 for(int i=0;i<temp.length;i++){  
 if(temp[i]>='A' && temp[i]<='Z')
 {
 big=big+1;
 }
 else if(temp[i] >= 'a' && temp[i]<='z')
 {
 small=small+1;
 }
 }
//第一种,判断是否全为大写
 if(big==temp.length){
 flag=true;
 return flag;
 }
//第二种,判断是否全为小写
 else if(small==temp.length){
 flag=true;
 return flag;
 }
 else if(temp[word.length()-1]>='A' && temp[word.length()-1]<='Z'&&big==1 && small==(temp.length-1)){
 flag=false;
 return flag;
 }
 else if(big==1 && small==(temp.length-1) && temp[0]>='A' && temp[0]<='Z')
 {
 flag=true;
 }
   
 System.out.println("big:"+big+",small:"+small); 
 return flag;
    }
}
0 0
原创粉丝点击