LeetCode: 520. Detect Capital
来源:互联网 发布:java实现二分查找算法 编辑:程序博客网 时间:2024/06/05 14:57
LeetCode: 520. Detect Capital
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.
自己的答案:
public class Solution { public boolean detectCapitalUse(String word) { if (word == null) { return false; } int length = word.length(); if (length == 1) { return true; } String first = word.substring(0, 1); String temp = word.substring(1); if (temp.toLowerCase().equals(temp)) { return true; } if (first.toUpperCase().equals(first)) { if (temp.toUpperCase().equals(temp)) { return true; } } return false; }}
最快的答案:
public class Solution { public boolean detectCapitalUse(String word) { boolean flag = true; if (((int)word.charAt(0) >64)&&((int)word.charAt(0) <=90)){ if (word.length()>=2){ if (((int)word.charAt(1) >64)&&((int)word.charAt(1) <=90)) for (int i =2; i < word.length(); i++){ if (!(((int)word.charAt(i) >=65)&&((int)word.charAt(i) <=90))) flag = false; } else{ for (int i =1; i < word.length(); i++){ if ((((int)word.charAt(i) >=65)&&((int)word.charAt(i) <=90))) flag = false; } } } } else{ for (int x =0; x < word.length(); x++){ if ((((int)word.charAt(x) >64)&&((int)word.charAt(x) <=90))) flag = false; } } if (flag) return true; else return false; }}
最简洁的答案:
public boolean detectCapitalUse(String word) { return word.matches("[A-Z]*|[A-Z]?[a-z]*");}
Simple Java Solution O(n) time O(1) space
- 【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
- 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
- SAP MM部分常用增强-ME21N-MIGO-MB1A
- Linux 停止,启动 weblogic(重启weblogic)
- leetcode 13. Roman to Integer
- Android 动态获取资源的ID
- 删除字符串中的某指定单词(不区分大小写)
- LeetCode: 520. Detect Capital
- Java项目服务器cpu占用100%解决办法
- Uncode系列开源组件简介
- Prime permutations Problem 49
- eclipse.ini
- U-net神经网络
- 【JavaScript】方法代码片
- SSD目标检测
- 深入理解 Spring 事务原理