題目: LeetCode - 520. Detect Capital

題目說明

給一個 String 代表一個單字,求單字是否符合以下條件:

  • 所有字母都為大寫
  • 所有字母都為小寫
  • 只有第一個字母為大寫

解題思路

紀錄大寫字母的數量及最後一個大寫字母的 index,最後再判斷即可。

參考解法

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
bool detectCapitalUse(string word) {
int index, count = 0, n = word.size();
for(int i = 0; i < n; ++i)
if(word[i] >= 'A' && word[i] <= 'Z')
++count, index = i;
if(!count || (count == 1 && index == 0) || count == n)
return true;
return false;
}
};