Detect Capital

来源:互联网 发布:十大网络主播评选排名 编辑:程序博客网 时间:2024/06/03 06:00

题目地址:https://leetcode.com/problems/detect-capital/?tab=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:

  1. All letters in this word are capitals, like “USA”.
  2. All letters in this word are not capitals, like “leetcode”.
  3. 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.

题目检查单词大写字母的书写是否符合规范:

  • 假如首字母是大写字母
    • 如果第二个字母是大写
      • 如果后面的字符全部大写,返回true;
      • 否则返回false;
    • 否则
      • 如果后面的字符全部小写,返回true;
      • 否则返回false;
  • 假如首字母是小写字母
    • 如果第二个字母后面(包含)的字母全部是小写,那么返回true;
    • 否则返回false;

分支结构大致如此:

public class DetectCapital {    public static boolean detectCapitalUse(String word) {        if (word.length() <= 1)            return true;        // The first letter is lowercase        if (word.charAt(0) >= 'a' && word.charAt(0) <= 'z') {            for (int i = 1; i < word.length(); i++) {                if (word.charAt(i) >= 'A' && word.charAt(i) <= 'Z')                    return false;            }            return true;        } else { // The first letter is uppercase            if (word.charAt(1) >= 'A' && word.charAt(1) <= 'Z') { // The second letter is uppercase                if (word.length() >= 3) {                    for (int i = 2; i < word.length(); i++) {                        if (word.charAt(i) >= 'a' && word.charAt(i) <= 'z')                            return false;                    }                    return true;                }                return true;            } else { // The second letter is lowercase                if (word.length() >= 3) {                    for (int i = 2; i < word.length(); i++) {                        if (word.charAt(i) >= 'A' && word.charAt(i) <= 'Z')                            return false;                    }                    return true;                }                return true;            }        }    }    public static void main(String[] args) {        System.out.println(detectCapitalUse("gooGle"));    }}

时间复杂度为:O(n)。

0 0
原创粉丝点击