2023年7月25日 星期二

7/25 每日一題(字串處理)

 We define the usage of capitals in a word to be right when one of the following cases holds:

  • All letters in this word are capitals, like "USA".
  • All letters in this word are not capitals, like "leetcode".
  • Only the first letter in this word is capital, like "Google".

Given a string word, return true if the usage of capitals in it is right.

 

Example 1:

Input: word = "USA"
Output: true

Example 2:

Input: word = "FlaG"
Output: false

 

Constraints:

  • 1 <= word.length <= 100
  • word consists of lowercase and uppercase English letters.


----------字串

class Solution:
    def detectCapitalUse(self, word: str) -> bool:
        if word == word.lower():
            return True
        elif word[0]==word[0].upper() and word[1:]==word[1:].lower():
            return True
        elif word == word.upper():
            return True
        else:
            return False

------------正則表達式


class Solution:
    def detectCapitalUse(self, word: str) -> bool:
        if re.findall(r'\b[A-Z]?[a-z]+\b',word): 
            #符合開頭是1或0個大寫 小寫結尾
            return True
        elif re.findall(r'\b[A-Z]+\b',word): #符合大寫開頭一直到大寫結尾
            return True
        
        else:
            return False



標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁