“This is the 22nd day of my participation in the First Challenge 2022. For details: First Challenge 2022”
describe
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
Copy the code
Note:
1 <= word.length <= 100
word consists of lowercase and uppercase English letters.
Copy the code
parsing
We define the use of uppercase in a word as correct when one of the following is true:
- All the letters in this word are capitalized, like “USA”.
- All letters in this word are not uppercase, as in “leetcode”.
- Only the first letter of the word is capitalized, like “Google.”
Given a string word, return true if the uppercase letters are used correctly. This is a basic string capitalization test. Python’s built-in functions are easy to use:
- String. Islower (), all characters in lower case, returns true, False otherwise
- String. Isupper (), all characters are uppercase, return true, False otherwise
- String. Istitle (), all words are capitalized, return true if true, False otherwise
Islower () or word.isupper() or word.istitle() is True.
answer
class Solution(object):
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
return word.islower() or word.isupper() or word.istitle()
Copy the code
The results
Given in the Python online submission for detection of Capital. Memory Usage: 13.3 MB, less than 83.94% of Python online submissions for Detect Capital.Copy the code
parsing
Although the above built-in function is convenient, but I still want to implement the relevant algorithm, just for practice, the idea is also very simple, is to write three functions, respectively judge these three cases, if any one is True, then return True. If self.islowerorTitle (word) or self.isupper(word) is True: self.islowerorTitle (word)
- IslowerOrTitle: True if the first character is lowercase or uppercase, as long as the following characters are lowercase from the second character
- Isupper: True as long as all letters are uppercase
answer
class Solution(object):
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
return self.islowerOrTitle(word) or self.isupper(word)
def islowerOrTitle(self, s):
for c in s[1:]:
if not 97<=ord(c)<=122:
return False
return True
def isupper(self, s):
for c in s:
if not 64<=ord(c)<=90:
return False
return True
Copy the code
The results
Given in the Python online submission for detection of Capital. Memory Usage: 13.6 MB, less than 8.81% of Python online submissions for Detect Capital.Copy the code
The original link
Leetcode.com/problems/de…
Your support is my biggest motivation