520. 检测大写字母

https://leetcode-cn.com/problems/detect-capital/

解法一:常规

用tolower()函数,将字符ch转为小写,然后利用asc码,已知小写字符比大写字符的asc大32(如’a’=97, ‘A’=65),用tolower(c)-c,结果只有两种:若c是小写,结果为0;大写则为32.

然后套上面规则即可.

class Solution {
public:
    bool detectCapitalUse(string word) {
        bool res = true;  //结果,初始为真
        int n = word.length();
        vector<int> tmp(n);
        for (int i = 0; i < n; i++) 
            tmp[i] = tolower(word[i]) - word[i];
        if (tmp[0]) {  //第一位是大写
            if (tmp[1]) {  //第二位也是大写,则后面都必须为大写(规则1)
                for (int i = 2; i < n; i++) {
                    if (!tmp[i]) return false;  //有一个不符合,结果为假
                }
            } else if (!tmp[1]) {  //第二位值小写,则后面都必须为小写(规则3)
                for (int i = 2; i < n; i++) {
                    if (tmp[i]) return false;
                }
            }
        } else if (!tmp[0]) {  //若第一位为小写,则后面都必须为小写(规则2)
            for (int i = 1; i < n; i++) {
                if (tmp[i]) return false;
            }
        }
        return res;
    }
};

解法二:py一行搞定

善用str函数

class Solution:
    def detectCapitalUse(self, word: str) -> bool:
        return word.islower() or word.isupper() or word.istitle()
        #或者
        #return word.upper()==word or word.lower()==word or word.title()==word

最后更新于