题目描述
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.
例子
例子 1
Input: “USA” Output: True
例子 2
Input: “FlaG” Output: False
解题思路
这道题目比较简单,合法单词一共就三类: 1. 全大写, 2. 首字母大写, 3. 全小写; 首先通过首字母判断是不是全小写;再根据第二个字母判断是不是全大写;最后根据属于哪种情况遍历一遍字符串发现不合法直接返回 false
就可以了,代码如下:
class Solution {
public:
bool detectCapitalUse(string word) {
if (word.length() <= 1) return true;
bool is_all_capital = false;
if (isupper(word[1])) {
if (!isupper(word[0])) return false;
else is_all_capital = true;
}
for (int i = 2; i < word.length(); i++) {
if (is_all_capital ^ (bool)(std::isupper(word[i]))) {
return false;
}
}
return true;
}
};
- 时间复杂度: O(n)
- 空间复杂度: O(1)