520. Detect Capital(檢測大寫字母)
阿新 • • 發佈:2019-02-15
題目
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