LeetCode 520. Detect Capital(检查大写)
题目描述
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 if it has more than one letter, like "Google".
Otherwise, we define that this word doesn't use capitals in a right way.
Example 1:
Input: "USA"
Output: True
Example 2:
Input: "FlaG"
Output: False
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
解法一
思路
不妨看看哪些情况是不满足要求的:
ABCd
,即有超过一个大写字母时,出现小写。abCd
,即有小写字母时,大写字母不在第一个。
所以当遍历字母时,只需要记录三个布尔变量saw_lower
、saw_one_upper
和saw_two_upper
:
- 字母是大写时:如果已经有小写字母(
saw_lower == True
),则返回False
;否则,如果已经有大写字母(saw_one_upper == True
)则置saw_two_upper
为True
,如果没有大写字母(saw_one_upper == False
),则置saw_one_upper
为True
。 - 字母是小写时:如果已经有两个大写字母(
saw_two_upper == True
),则返回False
;否则,置saw_lower
为True
。 - 如果处理过程中途未返回,则返回
True
。
Python
class Solution(object):
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
saw_lower = False
saw_one_upper = False
saw_two_upper = False
for letter in word:
if letter >= 'A' and letter <= 'Z':
if saw_lower:
return False
if saw_one_upper:
saw_two_upper = True
else:
saw_one_upper = True
if letter >= 'a' and letter <= 'z':
if saw_two_upper:
return False
saw_lower = True
return True
Java
public class Solution {
public boolean detectCapitalUse(String word) {
boolean sawLower = false;
boolean sawOneUpper = false;
boolean sawTwoUpper = false;
for (char letter : word.toCharArray()) {
if (letter >= 'A' && letter <= 'Z') {
if (sawLower) {
return false;
}
if (sawOneUpper) {
sawTwoUpper = true;
} else {
sawOneUpper = true;
}
}
if (letter >= 'a' && letter <= 'z') {
if (sawTwoUpper) {
return false;
}
sawLower = true;
}
}
return true;
}
}
C++
class Solution {
public:
bool detectCapitalUse(string word) {
bool sawLower = false;
bool sawOneUpper = false;
bool sawTwoUpper = false;
for (auto letter : word) {
if (letter >= 'A' && letter <= 'Z') {
if (sawLower) {
return false;
}
if (sawOneUpper) {
sawTwoUpper = true;
} else {
sawOneUpper = true;
}
}
if (letter >= 'a' && letter <= 'z') {
if (sawTwoUpper) {
return false;
}
sawLower = true;
}
}
return true;
}
};