520.Detect Capital(String-Easy)
发布日期:2021-06-30 11:46:55
浏览次数:2
分类:技术文章
本文共 1513 字,大约阅读时间需要 5 分钟。
转载请注明作者和出处:
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)全为大写字母;(2)全为小写字母;(3)只有首字母大写,其余字母小写。
思路:
a) C++
初始化一个记录字符串中含有大写字符数量的变量。遍历字符串的每一个字符,如果字符为大写字母,则大写字母计数变量计数一次(加一)。
合法条件:
- 大写字母计数变量为0(全为小写字母);
- 大写字母计数变量为字符串长度(全为大写字母);
- 大写字母计数变量为1且字符串首字符为大写(只有首字母大写,其余字母小写 )。
b) Python
Python提供了可以直接调用的API接口:
- isupper() 方法检测字符串中所有的字母是否都为大写;
- islower() 方法检测字符串是否由小写字母组成;
- istitle() 方法检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。
代码:
Language : cpp
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
class Solution(object): def detectCapitalUse(self, word): """ :type word: str :rtype: bool """ return word.isupper() or word.islower() or word.istitle()
代码获取:
转载地址:https://jackcui.blog.csdn.net/article/details/73495803 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2024年04月12日 18时43分40秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Apache Lucene Java 全文检索引擎架构
2019-04-30
Apache Arrow 内存数据交换格式
2019-04-30
OpenDocument Format ODF
2019-04-30
用Redis实现Session功能
2019-04-30
基础介绍-红黑树-数据结构
2019-04-30
基本操作及Java代码实现-红黑树-数据结构和算法
2019-04-30
插入与Java代码实现-红黑树-数据结构和算法
2019-04-30
删除及Java代码实现-红黑树-数据结构和算法
2019-04-30
Springboot内部类加注解失效的原因分析和解决方案
2019-04-30
Hbase与Hive的关系
2019-04-30
java工具类解压缩zip和rar
2019-04-30
java获取服务器启动时间
2019-04-30
正则中的 (?i) (?s) (?m) (?is) (?im)
2019-04-30
获取html中文档的所有img标签
2019-04-30
Java获取字符串单词个数
2019-04-30
软件安装向导jquery.steps.js
2019-04-30
require.js入门
2019-04-30
scss入门
2019-04-30
markdown编辑器示例
2019-04-30
@RequestParam与@PathVariable的区别
2019-04-30