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

原创粉丝点击