LeetCode 520. 检测大写字母(C、python)

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

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

  1. 全部字母都是大写,比如"USA"。
  2. 单词中所有字母都不是大写,比如"leetcode"。
  3. 如果单词不只含有一个字母,只有首字母大写, 比如 "Google"。

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

C

bool detectCapitalUse(char* word) 
{
    int n=strlen(word);
        int M=0;
        int m=0;
        if(n<2)
        {
            return true;
        }
        else
        {
            char temp=word[0];
            for(int i=0;i<n;i++)
            {
                if(word[i]>='A' && word[i]<='Z')
                {
                    M++;
                }
                if(word[i]>='a' && word[i]<='z')
                {
                    m++;
                }                
            }
            if((temp>='A' && temp<='Z' && M==1) || M==n || m==n)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
}

python

class Solution:
    def detectCapitalUse(self, word):
        """
        :type word: str
        :rtype: bool
        """
        M=0
        m=0
        n=len(word)
        if n<2:
            return True
        else:
            temp=word[0]
            for i in range(0,n):
                if ord(word[i])>=ord('A') and ord(word[i])<=ord('Z'):
                    M += 1
                if ord(word[i])>=ord('a') and ord(word[i])<=ord('z'):
                    m += 1
            if (ord(temp)>=ord('A') and ord(temp)<=ord('Z') and M==1) or M==n or m==n:
                return True
            else:
                return False

猜你喜欢

转载自blog.csdn.net/qq_27060423/article/details/82779051