转载请注明作者和出处: http://blog.csdn.net/c406495762
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:
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.
题目:判断字符串大写字母使用的是否合法。合法条件:(1)全为大写字母;(2)全为小写字母;(3)只有首字母大写,其余字母小写。
思路:
a) C++
初始化一个记录字符串中含有大写字符数量的变量。遍历字符串的每一个字符,如果字符为大写字母,则大写字母计数变量计数一次(加一)。
合法条件:
b) Python
Python提供了可以直接调用的API接口:
代码:
Language : cpp
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)));
}
};
Language : python
class Solution(object):
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
return word.isupper() or word.islower() or word.istitle()
代码获取: