1. 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.
constraints :
- 1 <= word.length <= 100
- word consists of lowercase and uppercase English letters.
2. Algorithms
Ascii codes of alphabet a - z and A - Z are same as below :
- a - z : 97 - 122
- A - Z : 65 - 90
To fits the above three conditions, the lenght of lowercase should be len(word) or len(word) -1 or 0.
- Start
- Declare variable named count initialized to 0.
- Repeat the steps while traversing character of input string.
- If ascii code of current character is lower case(97 - 122), increment count by 1.
- If the value of count is len(word) - 1 and ascii code of first value is lower than 90, return True
- If the value of count is len(word) or 0, return True
- Else, return False.
- End
3. Codes
class Solution:
def detectCapitalUse(self, word: str) -> bool:
count = 0
for char in word :
if ord(char) >= 97 and ord(char) <= 122 :
count += 1
if count == len(word) - 1 and ord(word[0]) <= 90 :
return True
if count == len(word) or count == 0:
return True
return False
4. Conclusion
'LeetCode > Easy' 카테고리의 다른 글
530 Minimum Absolute Difference in BST (0) | 2022.09.05 |
---|---|
521 Longest Uncommon Subsequence I (0) | 2022.09.04 |
511 Game Play Analysis I (0) | 2022.09.03 |
509 Fibonacci Number (0) | 2022.09.03 |
507 Perfect Number (0) | 2022.09.03 |