알고리즘/LeetCode

520. Detect Capital

앤테바 2023. 1. 2. 20:36
반응형

 

문제)

520. Detect Capital

 

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.

 

 

솔루션1)

- word의 대문자 수를 먼저 센 다음 조건에 맞는지 체크

class Solution:
    def detectCapitalUse(self, word: str) -> bool:        
        capital_count = sum([1 for c in word if 'A' <= c <= 'Z'])
        if capital_count == len(word):
            # All letters in this word are capitals, like "USA".
            return True
        elif capital_count == 0:
            # All letters in this word are not capitals, like "leetcode".
            return True
        elif capital_count == 1 and ('A' <= word[0] <= 'Z'):
            # Only the first letter in this word is capital, like "Google".
            return True
        else:
            return False

솔루션2)

- isupper(), islower(), istitle() 내장 함수 사용

class Solution:
    def detectCapitalUse(self, word: str) -> bool:        
        return word.isupper() or word.islower() or word.istitle()

islower() Function in python checks whether the input string is in lowercase
isupper() Function in python checks whether the input string is in uppercase
istitle() Function in python checks whether the input string is in title case

출처 : https://www.datasciencemadesimple.com/lower-upper-title-function-python/
반응형