Leetcode 520 Detect Capital
来源:互联网 发布:排序算法及时间复杂度 编辑:程序博客网 时间:2024/05/16 17:24
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.
天呐,终于做到了到目前为止感觉最简单的一道题。
题目表明以上三种情况返回true。
代码如下,只要分情况讨论即可。
public static boolean detectCapitalUse(String word) { //全部为大写字母 int count1 = 0; for (int i = 0; i < word.length(); i++) { if (word.charAt(i)<='Z'&&word.charAt(i)>='A') { count1++; } } //全部为小写字母 int count2 = 0; for (int i = 0; i < word.length(); i++) { if (word.charAt(i)<='z'&&word.charAt(i)>='a') { count2++; } } //第一个为大写,其他的为小写 int flag = 0; if (word.charAt(0)<='Z'&&word.charAt(0)>='A') { flag = 1; } int count3 = 0; if (flag==1) { for (int i = 1; i <word.length(); i++) { if (word.charAt(i)<='z'&&word.charAt(i)>='a') { count3++; } } } //判断返回 if (flag==1&&count3==word.length()-1) { return true; } if (count1==word.length()||count2==word.length()) { return true; } return false; }
但是别人的答案是这样写的:
return word.matches("[A-Z]+|[a-z]+|[A-Z][a-z]+");
但是这样虽然简单,他的运行时间是我的五倍左右。
阅读全文
0 0
- 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 C++
- leetcode 520[easy]---Detect Capital
- LeetCode 520:Detect Capital (c++)
- LeetCode 520 Detect Capital 检测大写
- 【Leetcode】520. Detect Capital
- LeetCode 520. Detect Capital
- LeetCode 520. Detect Capital
- LeetCode:Detect Capital
- sessionid如何产生?由谁产生?保存在哪里?
- Highcharts 个人笔记
- cookie记住密码
- (三) Freemarker 常用指令
- ios-应用程序间跳转
- Leetcode 520 Detect Capital
- (四)Freemarker 运算符
- 编码习惯之接口定义
- java环境变量设置
- 5+sdk插件开发,并离线打包apk
- MySQL拼音首字母查询(支持三个中文以内的查询)
- 机器学习实践指南
- (五)Freemarker 整合Spring
- 物料管理的容差范围维护