【LeetCode】Detect Capital 解题报告
来源:互联网 发布:网络公会白马义从 编辑:程序博客网 时间:2024/05/20 15:10
【LeetCode】Detect Capital 解题报告
标签(空格分隔): LeetCode
题目地址:https://leetcode.com/problems/detect-capital/#/description
题目描述:
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 :
Input: "USA"Output: TrueInput: "FlaG"Output: False
Ways
往往简单的方法就最有效。这个题说了有三种情况,那我就判断三种情况,如果有一个情况满足就可以。在判断是否满足全大写的时候,如果有一个字母是小写,那么就判断为false,然后break;就好了。就这样判断了三次,最后如果有一个是true,即可返回是。
这样的一个缺点就是如果已经判断是全大写,还要判断其他的,当然可以写if语句判断,但是我感觉有点啰嗦,还不如直接三个情况都判断简单。
public class Solution { public boolean detectCapitalUse(String word) { if(word == null || word.length() == 0){ return false; } int len = word.length(); boolean isUpper = true;//全大写 boolean isLower = true;//全小写 boolean isFirst = true;//首字母大写 for(int i = 0; i < len; i++){ if(word.charAt(i) >= 'a' && word.charAt(i) <= 'z'){ isUpper = false; break; } } for(int i =0; i < len; i++){ if(word.charAt(i) >= 'A' && word.charAt(i) <= 'Z'){ isLower = false; break; } } if(word.charAt(0) >= 'a' && word.charAt(0) <= 'z'){ isFirst = false; } for(int i = 1; i < len; i++){ if(word.charAt(i) >= 'A' && word.charAt(i) <= 'Z'){ isFirst = false; break; } } return isLower || isUpper || isFirst; }}
看到了别人的更简洁的做法,统计大写字母的个数,有0个或者全是大写,或者只有一个大写并且在首位。
public class Solution { public boolean detectCapitalUse(String word) { int cnt = 0; for(char c: word.toCharArray()) if('Z' - c >= 0) cnt++; return ((cnt==0 || cnt==word.length()) || (cnt==1 && 'Z' - word.charAt(0)>=0)); }}
Date
2017 年 4 月 3 日
0 0
- 【LeetCode】Detect Capital 解题报告
- [Leetcode] 520. Detect Capital 解题报告
- 【Leetcode】520. Detect Capital
- LeetCode 520. Detect Capital
- leetcode-520-Detect Capital
- LeetCode 520. Detect Capital
- LeetCode:Detect Capital
- LeetCode-520. Detect Capital
- Leetcode #520 Detect Capital
- leetcode 520. Detect Capital
- leetcode 520. Detect Capital
- [leetcode] 520. Detect Capital
- [LeetCode]520 Detect Capital
- [LeetCode]520. Detect Capital
- LeetCode | 520. Detect Capital
- 【LeetCode】520. Detect Capital
- LeetCode 520. Detect Capital
- leetcode 520. Detect Capital
- 设计模式
- ArrayList
- 1509: [NOI2003]逃学的小孩
- unity反馈消息到ios Unity与ios交互
- Gentoo下折腾emerge包管理器
- 【LeetCode】Detect Capital 解题报告
- Spring AOP 必导jar包
- laravel5.2 验证码
- 大小端问题
- Unity与ios交互
- Calendar日历+Date时间+SimpleDateFormat转换格式
- Xmind之鱼骨图绘制方法
- getopt解析函数
- 第一篇(Hay For Sale 购买干草)【动规】