题目:
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".
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.
翻译:
你需要判断大写字母的使用是否正确。
我们定义一个词语的的大写字母使用正确当它满足以下的情况之一:
- 词语中的所有字母都是大写的,像“USA”。
- 词语中的所有字母都没有大写,像“leetcode”。
- 词语中有超过一个字母时,并且只有第一个字母是大写的。
否则,我们定义这个词没有正确使用大写字母。
例子 1:
输入: "USA" 输出: True
例子 2:
输入: "FlaG" 输出: False
注意: 输入是非空的包含大写和小写字母的词语。
思路:
首先判断词语中的字符是否为大写,记下大写字母的个数cnt,然后,根据规则判断是否是正确使用大写字母的情况。如果,cnt等于0,则说明所有的字母都是小写的,返回真;如果cnt等于词语中字母的个数,则说明所有的字母都是大写的,返回真;如果cnt=1,只有一个字母是大写的,并且这个大写的字母是词语的第一个字母,则返回真。
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
bool detectCapitalUse(string word) {
int cnt = 0;
for (int i = 0; i < word.size(); i++) {
if (word[i] >= 'A'&&word[i] <= 'Z')
cnt++;
}
if (cnt == word.size() || cnt == 0 || (cnt == 1 && word[0] >= 'A'&&word[0] <= 'Z'))
return true;
else return false;
}
};
int main()
{
Solution s;
string word = "FlaG";
bool result = s.detectCapitalUse(word);
cout << result << endl;
return 0;
}