LeetCode笔记:520. Detect Capital
2023-03-15 23:24:11 时间
问题(Easy):
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".
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.
大意:
给出一个单词,你需要判断其大写的使用是否正确。 我们定义单词中大写的用法在下面的情况下是正确的:
- 所有的字母都是大写,比如“USA”。
- 所有的字母都不是大写,比如“leetcode”。
- 如果有多个字母,只有首字母是大写的,比如“Google”。
否则,我们认为单词没有正确地使用大写。 例1: 输入:“USA” 输出:True 例2: 输入:“FlaG” 输出:False 注意:输入会是一个非空单词,由大小写字母组成。
思路:
没什么取巧的方法,无非是判断三个条件是否成立,要么全是大写,要么只有首字母是大写。
代码(C++):
class Solution {
public:
bool detectCapitalUse(string word) {
bool canBig = true;
int bigNum = 0;
for (auto c : word) {
if (c - 'a' < 0) {
if (!canBig) return false;
bigNum++;
}
else if (c - 'a' >= 0) {
if (bigNum > 1) return false;
canBig = false;
}
}
return true;
}
};
或者从大写字母的数量和位置来一起判断:
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));
}
};
合集:https://github.com/Cloudox/LeetCode-Record
相关文章
- 2016年十大最热门 IT 职业岗位
- 零编程经验的我是如何找到工作的
- 不懂程序看的明白《黑客帝国》吗?
- 假如你想成为全栈工程师…
- JavaMail 保证邮件发送成功的方法总结
- 如何让你的程序员不要厌倦工作?
- 程序员最恐怖的噩梦是什么?
- 15 个实用的 PHP 正则表达式
- 程序体积优化的十个小妙招
- Java 9因模块化进程缓慢而欲推迟发布
- 写在 PHP7 发布之际一些话
- 这些 Nginx 负载均衡配置误区,运维请注意
- 有人在Github上用几行代码就造了个锤子便签
- 做过程序员的产品经理是一种什么样的存在?
- PHPUnit 在 Windows 下的配置及使用教程
- 程序开发人员缺乏经验的7种表现
- 一个单例还能写出花来吗?
- 关于容器,你需要知道这7件事
- 程序员如何在职场中实现“跨越式”成长?
- 成为一名更好的程序员:如何阅读源代码