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:

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

很简单的一道题 偷懒不想用函数了。

class Solution {
    public boolean detectCapitalUse(String word) {
        if(word==null||word.length()==0) return false;
        int len =word.length();
        char ch1 = word.charAt(0);
        if(ch1>='A'&&ch1<='Z')
        {
            if(len==1)
                return true;
            char ch2 = word.charAt(1);
            if(ch2>='A'&&ch2<='Z')
            {
                int pos = 1;
                while(pos<len&&(word.charAt(pos)>='A'&&word.charAt(pos)<='Z'))
                pos++;
                if(pos!=len)
                return false;
                return true;
            }
            else if(ch2>='a'&&ch2<='z')
            {
                int pos = 1;
              while(pos<len&&(word.charAt(pos)>='a'&&word.charAt(pos)<='z'))
                  pos++;
              if(pos!=len)
                return false;
            return true;
            }
            else
                return false;
        }
        else if(ch1>='a'&&ch1<='z')
        {
            if(len==1)
                return true;
            int pos = 1;
            while(pos<len&&(word.charAt(pos)>='a'&&word.charAt(pos)<='z'))
                pos++;
            if(pos!=len)
                return false;
            return true;
        }
        else
        {
            return false;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容