本文主要是介绍LeetCode 520. 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:
- 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.
思路:
思路其实就是如果长度为1,直接返回true;如果长度大于1,分了四种情况,具体见代码注释。
代码:
class Solution {
public:bool detectCapitalUse(string word) {int len=word.length();//计算word的长度if(len==1){//如果长度为1,直接返回truereturn true;}for(int i=1;i<len;++i){//长度大于1的情况if(isupper(word[0])&&isupper(word[1])){//如果第一位和第二位都为大写if(isupper(word[i])){//如果i位是大写,继续循环continue;}else{//否则直接返回falsereturn false;}}if(isupper(word[0])&&islower(word[1])){//如果第一位为大写而第二五公里为小写if(islower(word[i])){//如果从i位开始一直是小写,继续循环 continue;}else{//否则返回falsereturn false;}}if(islower(word[0])&&islower(word[1])){//如果第一位和第二位都为小写if(islower(word[i])){//如果从i位开始一直是小写,继续循环continue;}else{//否则返回falsereturn false;}}if(islower(word[0])&&isupper(word[1])){//如果第一位为小写而第二位为大写return false;//直接返回false}}return true;//如果循环结束没返回false,那一定符合要求}
};
**输出结果:**9ms
这篇关于LeetCode 520. Detect Capital的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!