Last Updated on 2022-01-24 by Clay
題目
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"
.
Given a stringword
, returntrue
if the usage of capitals in it is right.
Example 1:
Input: word = "USA" Output: true
Example 2:
Input: word = "FlaG" Output: false
Constraints:
1 <= word.length <= 100
word
consists of lowercase and uppercase English letters.
題目輸入文字,若文字符合全部都是大寫、全部都是小寫、只有第一個字是大寫其他全部都是小寫...... 則回傳 true;反之則回傳 false。
解題思路
這題非常單純,首先只需要判斷文字長度是不是只有 1,只有 1 的情況無論大小寫都是回傳 true。
接下來,則判斷第一個字母跟第二個字母的相異情況,除了第一個字母小寫第二個字母大寫外,其他情況皆為合法字串。
接下來,就是把字串中的第二個字元開始跑一遍,如果字元跟相鄰的字元大小寫不相同,則可以立刻回傳 false。
如果掃完一遍後發覺都相同,則回傳 true。
複雜度
Time Complexity | O(n) |
Space Complexity | O(1) |
C++ 範例程式碼
class Solution {
public:
bool detectCapitalUse(string word) {
// Base case
if (word.size() == 1) return true;
if (!isupper(word[0]) && isupper(word[1])) return false;
for (int i=1; i<word.size()-1; ++i) {
if (isupper(word[i]) != isupper(word[i+1])) return false;
}
return true;
}
};
Python 範例程式碼
class Solution:
def detectCapitalUse(self, word: str) -> bool:
# Base case
if len(word) == 1: return True
if not word[0].isupper() and word[1].isupper(): return False
for i in range(1, len(word)-1):
if word[i].isupper() != word[i+1].isupper(): return False
return True