python--leetcode.Detect Capital

来源:互联网 发布:HIS系统数据库类型 编辑:程序博客网 时间:2024/06/07 10:32

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:

  1. All letters in this word are capitals, like "USA".
  2. All letters in this word are not capitals, like "leetcode".
  3. 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

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.

题目意思就是给你一个字符串,判断它是不是全为大写或小写。或者开头为大写其他为小写。

解题思路:把该字符串全部转化为大写或小写,判断跟原字符串是否相等。

class Solution(object):    def detectCapitalUse(self, word):        """        :type word: str        :rtype: bool        """        if(word.lower()== word):  return True        elif (word.upper()==word) : return True        elif(word[0].upper()==word[0] and word[1:].lower()==word[1:]):return True        else:return Falses=Solution()print(s.detectCapitalUse('Fflk'))
用python的库可以更方便地解决这一题....一行代码:

def detectCapitalUse(self, word):    return word.isupper() or word.islower() or word.istitle()


原创粉丝点击