“This is the 13th day of my participation in the November Gwen Challenge. See details: The Last Gwen Challenge 2021”.

Topic describes

This is 520 on LeetCode. Detect capital letters, difficulty is simple.

Tag: “Simulation”

We define that capitalizing a word is correct when:

  • All letters are uppercase, like “USA”.
  • All letters in words are not capitalized, such as “leetcode”.
  • If the word contains more than one letter, capitalize only the first letter, such as “Google”.

I give you a string word. Returns true if uppercase is used correctly; Otherwise, return false.

Example 1:

Input: word = "USA" output: trueCopy the code

Example 2:

Input: word = "FlaG" Output: falseCopy the code

Tip:

  • 1 <= word.length <= 100
  • Word consists of lowercase and uppercase letters

simulation

According to the meaning of the question, judge the three rules respectively.

Code:

class Solution {
    public boolean detectCapitalUse(String word) {
        if (word.toUpperCase().equals(word)) return true;
        if (word.toLowerCase().equals(word)) return true;
        int n = word.length(), idx = 1;
        if (Character.isUpperCase(word.charAt(0))) {
            while (idx < n && Character.isLowerCase(word.charAt(idx))) idx++;
        }
        returnidx == n; }}Copy the code
  • Time complexity: O(n)O(n)O(n), constant 555.
  • Spatial complexity: New strings will be generated during algorithm execution, and the complexity is O(n)O(n)O(n)

The last

This is the No.520 of our “Brush through LeetCode” series, which started on 2021/01/01. There are 1916 topics on LeetCode by the start date, some of which have locks, so we will finish all the topics without locks.

In this series of articles, in addition to explaining how to solve the problem, I will also present the most concise code possible. If a general solution is involved, the corresponding code template will also be used.

In order to facilitate the students to debug and submit the code on the computer, I set up the relevant warehouse: github.com/SharingSour… .

In the repository, you’ll see links to the series of articles, the corresponding code for the series of articles, the LeetCode source links, and other preferred solutions.