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:
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.
题意:判断一个字符串大小写使用是否合法。合法的情况有:全为大写;全为小写;只有第一个字母大写。
算法1
题解:如果字符串长度为1,总是合法的;否则我们先判断一下前两个字符是否合法,当第一个字符为小写,第二个字符为大写时不合法;否则,后序所有字符大小写应该与第二个字符相同。
C++ 代码
class Solution {
public:
int isupper(char c){ return ('A' <= c && c <= 'Z')?1:0;}
int islower(char c){ return ('a' <= c && c <= 'z')?1:0;}
bool detectCapitalUse(string word) {
int n = word.length();
if(n == 1) return true;
if(islower(word[0]) && isupper(word[1])) return false;
int upper = isupper(word[1]);
for(int i = 2 ; i < n ; i ++)
if(isupper(word[i]) ^ upper)
return false;
return true;
}
};