520. Detect Capital
来源:互联网 发布:冒险岛游戏数据库系统 编辑:程序博客网 时间:2024/06/04 00:20
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.
包括构思什么的想了三四个小时,思路可能不是很好,根据第一个字符和第二个字符的大小写排除三种不合法情况。
开始在return false 后面加了 break 后来发现是多余的,加break就是错的
class Solution {public: bool detectCapitalUse(string word) { int a=word.length(); if(word[0]>='a') { for (int i=1;i<a;i++) { if(word[i]<'a') return false; } return true; } if(word[0]<'a'&&word[1]<'a' ) { for (int i=2;i<a;i++) { if(word[i]>='a') return false; } return true ; } if(word[0]<'a'&&word[1]>='a' ) { for (int i=2;i<a;i++) { if(word[i]<'a') return false; } return true; } } };
发现一个简单点的答案(思路一样,我忘了 isupper 和 islower):
题目大意:判断一个字母是否大小写正确:要么全是大写,要么全是小写,或者首字母大写其他小写,否则不满足题意~
分析:判断word[0]和word[1]的大小写,如果word[0]是小写,那后面必须是小写,如果word[0]是大写word[1]是小写,那后面也必须是小写,如果word[0]是大写word[1]也是大写那么后面必须都是大写~
class Solution {public: bool detectCapitalUse(string word) { if (word.length() <= 1) return true; if (islower(word[0]) || (isupper(word[0]) && islower(word[1]))) { for (int i = 1; i < word.length(); i++) if (isupper(word[i])) return false; } else { for (int i = 1; i < word.length(); i++) if (islower(word[i])) return false; } return true; }};
这道题给了我们一个单词,让我们检测大写格式是否正确,规定了三种正确方式,要么都是大写或小写,要么首字母大写,其他情况都不正确。那么我们要做的就是统计出单词中所有大写字母的个数cnt,再来判断是否属于这三种情况,如果cnt为0,说明都是小写,正确;如果cnt和单词长度相等,说明都是大写,正确;如果cnt为1,且首字母为大写,正确,其他情况均返回false,参见代码如下:
解法一:
class Solution {public: bool detectCapitalUse(string word) { int cnt = 0, n = word.size(); for (int i = 0; i < n; ++i) { if (word[i] <= 'Z') ++cnt; } return cnt == 0 || cnt == n || (cnt == 1 && word[0] <= 'Z'); }};
- 【Leetcode】520. Detect Capital
- 520. Detect Capital (E)
- LeetCode 520. Detect Capital
- LeetCode 520. Detect Capital
- 520. Detect Capital
- LeetCode-520. Detect Capital
- 520. Detect Capital
- leetcode 520. Detect Capital
- 520. Detect Capital
- 520. Detect Capital
- 520. Detect Capital
- 520. Detect Capital
- leetcode 520. Detect Capital
- [leetcode] 520. Detect Capital
- 520. Detect Capital Easy
- 520. Detect Capital
- [LeetCode]520. Detect Capital
- 520. Detect Capital
- ASP.NET Core轻松入门之Middleware管道模型
- 内存管理
- 3个著名加密算法(MD5、RSA、DES)的解析
- RabbitMQ(四)
- git 应用 merge
- 520. Detect Capital
- Python的变量以及运算符
- 购物车和订单
- docker pull 过程distribution源码 分析
- 带你逐步深入了解SSM框架——SpringMVC框架详解
- GLSL加速类图解
- Git免密码登录
- IndentationError: unexpected indent,SyntaxError: invalid syntax,TypeError: object() takes no paramet
- C++实现排序算法