520. Detect Capital
Problem description:
Given a word, you need to judge whether the usage of capitals in it is right or not.
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”.
Otherwise, we define that this word doesn’t use capitals in a right way.
Example 1:1
2Input: "USA"
Output: True
Example 2:1
2Input: "FlaG"
Output: False
Solution:
The question mentioned given a word, so during the interview, we should starting from clarifying the input.
- Does the word contains numbers or symbols?
In the description, there’re three conditions to return True. So we could count the number of capital characters to verify.
1 | class Solution: |
Another thought is to check the condition of 1~n
. That is to say, character 1~n
should be all lower case or upper case. But an exception is the first character word[0]
is lower case but word[1~n]
is upper case.
Another thought is to check the condition of 1~n
. We should only return True
if the whole string is lower/upper case, or only first character is upper case and word[1:]
is lower case.
1 | class Solution: |
time complexity: $O(n)$
space complexity: $O(n)$
reference:
related problem: