欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 520. Detect Capital (python+cpp)

程序员文章站 2022-05-15 14:05:40
...

题目

Leetcode 520. Detect Capital (python+cpp)

解法:

只需要注意一下python里面is_upper的用法即可。C++里面直接进行比较就好
python版本

class Solution:
    def detectCapitalUse(self, word: str) -> bool:
        capital_pos = []
        for i,c in enumerate(word):
            if c.isupper():
                capital_pos.append(i)
        
        if len(capital_pos) == 0:
            return True
        elif len(capital_pos) == 1:
            return capital_pos[0] == 0
        else:
            return len(capital_pos)==len(word)

C++版本

class Solution {
public:
    bool detectCapitalUse(string word) {
        vector<int> capital_pos;
        for (int i=0;i<word.size();i++){
            if (word[i]>='A' and word[i]<='Z'){
                capital_pos.push_back(i);
            }
        }
        if (capital_pos.size()==0){
            return true;
        }
        else if (capital_pos.size()==1){
            return capital_pos[0]==0;
        }
        else{
            return capital_pos.size() == word.size();
        }
    }
};