LeetCode-Detect_Capital

题目:

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:

  1. All letters in this word are capitals, like "USA".
  2. All letters in this word are not capitals, like "leetcode".
  3. 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: True

Example 2:

Input: "FlaG"
Output: False

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.


翻译:

你需要判断大写字母的使用是否正确。

我们定义一个词语的的大写字母使用正确当它满足以下的情况之一:

  1. 词语中的所有字母都是大写的,像“USA”。
  2. 词语中的所有字母都没有大写,像“leetcode”。
  3. 词语中有超过一个字母时,并且只有第一个字母是大写的。

否则,我们定义这个词没有正确使用大写字母。


例子 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值