520. Detect Capital
Description
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.
Submitted Code
class Solution(object):
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
if word.isupper() or word.islower(): # 모두 대문자 또는 모두 소문자
return True
if word[0].isupper() and word[1:].islower(): # 첫 번째 문자만 대문자고 나머지는 소문자
return True
return False
Runtime: 0 ms | Beats 100.00%
Memory: 12.49 MB | Beats 51.59%
isupper() 또는 islower() 함수는 문자열의 모든 문자가 대문자 또는 소문자일때만 True를 반환한다.
첫 번째만 대문자고 나머지는 소문자인 케이스에는 문자열 슬라이싱을 사용했지만, istitle()을 사용하면 더 쉽게 해결할 수 있다.
Other Solutions
1st
class Solution(object):
def detectCapitalUse(self, word):
return word in [word.upper(), word.lower(), word.capitalize()]
time complexity: 𝑂(𝑛)
space complexity: 𝑂(1)
capitalize()는 문자열의 첫 번째 문자는 대문자, 나머지는 소문자가 되도록 변경한다.