算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 检测大写字母,我们先来看题面:
https://leetcode-cn.com/problems/detect-capital/
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, like "Google". Given a string word, return true if the usage of capitals in it is right.
我们定义,在以下情况时,单词的大写用法是正确的:
给你一个字符串 word 。如果大写用法正确,返回 true ;否则,返回 false 。
示例 1:
输入:word = "USA"
输出:true
示例 2:
输入:word = "FlaG"
输出:false
可以通过比较大写字母的个数与当前下标的大小来判断字符串是否连续大写,如果大写字母个数小于当前下标则返回false,最后再判断是否都是大写字母或者只有首字母大写。
class Solution {
public:
bool detectCapitalUse(string word) {
int upCt=0;
for(int i=0;i<word.length();i++) {
if(isupper(word[i])) {
if(upCt<i) {
return false;
}
upCt++;
}
}
return upCt==word.length() || upCt<=1;
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: