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

520.Detect Capital(String-Easy)

作者头像
Jack_Cui
发布2018-01-08 16:05:55
6490
发布2018-01-08 16:05:55
举报
文章被收录于专栏:Jack-CuiJack-Cui

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:

代码语言: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.

题目:判断字符串大写字母使用的是否合法。合法条件:(1)全为大写字母;(2)全为小写字母;(3)只有首字母大写,其余字母小写。

思路:

a) C++

    初始化一个记录字符串中含有大写字符数量的变量。遍历字符串的每一个字符,如果字符为大写字母,则大写字母计数变量计数一次(加一)。

合法条件:

  • 大写字母计数变量为0(全为小写字母);
  • 大写字母计数变量为字符串长度(全为大写字母);
  • 大写字母计数变量为1且字符串首字符为大写(只有首字母大写,其余字母小写 )。

b) Python

    Python提供了可以直接调用的API接口:

  • isupper() 方法检测字符串中所有的字母是否都为大写;
  • islower() 方法检测字符串是否由小写字母组成;
  • istitle() 方法检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。

代码:

Language : cpp

代码语言:javascript
复制
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)));
    }
};

Language : python

代码语言:javascript
复制
class Solution(object):
    def detectCapitalUse(self, word):
        """
        :type word: str
        :rtype: bool
        """
        return word.isupper() or word.islower() or word.istitle()

代码获取:

Github的LeetCode项目

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档