天天看点

LeetCode_520_检测大写字母

题目描述:

给定一个单词,你需要判断单词的大写使用是否正确。

我们定义,在以下情况时,单词的大写用法是正确的:

全部字母都是大写,比如"USA"。

单词中所有字母都不是大写,比如"leetcode"。

如果单词不只含有一个字母,只有首字母大写, 比如 “Google”。

否则,我们定义这个单词没有正确使用大写字母。

输入示例1:
输入: "USA"
输出: True      

算法思想:此题不需要按照一个一个字符遍历,判断字符是否合法。其实有个巧妙的方法,只需要统计字符串中大写字母的个数即可判断该字符串大小写是否合法。

输入示例2:
输入: "FlaG"
输出: False      
class Solution {
public:
    bool iscap(char c){
        if(c>='A'&&c<='Z')
            return true;
        return false;
    }
    bool detectCapitalUse(string word) {
        int len=word.size();
        int count=0;//统计字符串中大写字母的个数
        for(int i=0;i<len;i++){
            if(iscap(word[i]))
                count++;
        }
        if(count==len)//全是大写字母
            return true;
        else if(count==1&&iscap(word[0]))//首字母大写
            return true;
        else if(count==0)//全是小写字母
            return true;
        else 
            return false;
    }
};      
LeetCode_520_检测大写字母
class Solution {
public:
    bool detectCapitalUse(string word) {
        int uc = 0;
        for (int i = 0; i < word.size(); i++) {
            if (isupper(word[i]) && uc++ < i) {//isupper(char c)判断是否为大写字母。此用于判断是否是连续出现大写字母
                return false;
            }
        }
        
        return uc == word.size() || uc <= 1;//用于判断是否全大写或首字母大写或全小写
    }
};      
有bug的程序
class Solution {
public:
    bool isCapital(char c){
        if(c>='A'&&c<='Z')
            return true;
        else
            return false;
    }
    
    bool detectCapitalUse(string word) {
        int i=0;
        if(isCapital(word[0])){
            if(isCapital(word[1])){
                while(i<word.size()&&isCapital(word[i])){
                    i++;
                    if(i==word.size())
                        return true;
                }
                return false;
            }else{
                while(!isCapital(word[i])){
                    i++;
                    if(i==word.size())
                        return true;
                }
                return false;
            }
        }else{
            while(i<word.size()&&isCapital(word[i])){
                i++;
                return false;
            }
            return true;    
        }
        
    }
};