题目
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.
题意
给你一个单词,你需要去判断是the usage of capitals ,我们定义一个单词是the usage of capitals 当符合下面的三个条件中的一个:
1.单词所有字母都是大写字母,例如USA.
2.单词所有字母都不是大写字母,例如leetcode
3.单词中只有首字母大写。例如Google.
题解
C++代码
class Solution {
public:
bool detectCapitalUse(string word) {
string t = word, t1 = "", t2="", t3="";
for(int i=0; i<word.length(); i++)
{
if(word[i]>='a'&&word[i]<='z')//全大写
t1+=(word[i]-32);
else
t1+=word[i];
if(word[i]>='A'&&word[i]<='Z')//全小写
t2+=(word[i]+32);
else
t2+=word[i];
}
t3 = t2;
t3[0] = t1[0];
return t==t1 || t==t2||t==t3;
}
};
python代码
class Solution(object):
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
t = word
t1 = word.upper()
t2 = word.lower()
t3 = t2.title() #首字母大写
return t==t1 or t==t2 or t==t3