問題(Easy):
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: TrueExample 2:
Input: "FlaG"
Output: FalseNote: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
大意:
給出一個單詞窜管,你需要判斷其大寫的使用是否正確橄仍。
我們定義單詞中大寫的用法在下面的情況下是正確的:
- 所有的字母都是大寫韧涨,比如“USA”。
- 所有的字母都不是大寫侮繁,比如“l(fā)eetcode”虑粥。
- 如果有多個字母,只有首字母是大寫的宪哩,比如“Google”娩贷。
否則,我們認(rèn)為單詞沒有正確地使用大寫锁孟。
例1:
輸入:“USA”
輸出:True例2:
輸入:“FlaG”
輸出:False注意:輸入會是一個非空單詞育勺,由大小寫字母組成但荤。
思路:
沒什么取巧的方法罗岖,無非是判斷三個條件是否成立涧至,要么全是大寫,要么只有首字母是大寫桑包。
代碼(C++):
class Solution {
public:
bool detectCapitalUse(string word) {
bool canBig = true;
int bigNum = 0;
for (auto c : word) {
if (c - 'a' < 0) {
if (!canBig) return false;
bigNum++;
}
else if (c - 'a' >= 0) {
if (bigNum > 1) return false;
canBig = false;
}
}
return true;
}
};
或者從大寫字母的數(shù)量和位置來一起判斷:
class Solution {
public:
bool detectCapitalUse(string word) {
int cnt = 0;
for(char c: word) if('Z' - c >= 0) cnt++;
return ((cnt==0 || cnt==word.length()) || (cnt==1 && 'Z' - word[0]>=0));
}
};
合集:https://github.com/Cloudox/LeetCode-Record