520. Detect Capital
- Total Accepted: 16777
- Total Submissions: 31953
- Difficulty: Easy
- Contributors: love_Fawn
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".
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.
这道题目的题号很有意思520。。。。。。。。。。。。。。。。。。。。
该题目给出了三种情况:
1.全部大写
2.全部小写
3.首字母大写
首先当只有一个字母的时候,无论是大写还是小写,都是正确的
其次,首字母大写的话,其后字母必须是小写或者必须是大写,利用循环解决
如果首字母小写,其后必须是小写,也是利用循环来实现的
代码如下:
class Solution {
public:
bool detectCapitalUse(string word) {
if (word.length() <= 1) return true;
if (islower(word[0]) || (isupper(word[0]) && islower(word[1]))) {
for (int i = 1; i < word.length(); i++)
if (isupper(word[i])) return false;
} else {
for (int i = 1; i < word.length(); i++)
if (islower(word[i])) return false;
}
return true;
}
};