前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-520-Detect Capital

leetcode-520-Detect Capital

作者头像
chenjx85
发布2018-05-22 16:34:44
4690
发布2018-05-22 16:34:44
举报
文章被收录于专栏:chenjx85的技术专栏

题目描述:

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:

代码语言:javascript
复制
Input: "USA"
Output: True

Example 2:

代码语言:javascript
复制
Input: "FlaG"
Output: False

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

要完成的函数:

bool detectCapitalUse(string word) 

说明:

1、这道题目不难,其实就是判断单词的形式合不合法。题目给定了几个判断条件:

如果全部字母都是大写,那么合法。如USA

如果全部字母都是小写,那么合法。如leetcode

如果单词超过一个字符,且首字母大写,其余字母小写,那么合法。如Google

2、明白条件之后,我们来写判断语句。

代码如下:

代码语言:javascript
复制
    bool detectCapitalUse(string word) 
    {
        bool flag=1;
        if(word.size()==1)//边界条件
            return true;
        if(islower(word[1]))//第二个字母是小写,之后必须都是小写
        {
            for(int i=2;i<word.size();i++)
            {
                if(isupper(word[i]))
                {
                    flag=0;
                    break;
                }
            }
            if(flag==0)
                return false;
            else 
                return true;//无论首字母大小写均合法
        }
        else 
        {
            for(int i=2;i<word.size();i++)//第二个字母大写,其后必须大写
            {
                if(islower(word[i]))
                {
                    flag=0;
                    break;
                }
            }
            if(flag==0)
                return false;
            if(isupper(word[0]))//首字母大写,合法
                return true;
            else
                return false;//首字母小写,不合法
        }
        
    }

上述代码囊括了所有的判断情况,实测15ms,beats 57.47% of cpp submissions。

3、在讨论区中看到有人用了字符串匹配的方法来做这道题,只写了一行代码,但是实测效果很慢……

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-04-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档