↓Skip to main content
  1. LeetCode/

LeetCode 520: Detect Capital

·1 min· ·
LeetCode Easy String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-25

  • Submissions: Accepted (first try)

Approach
#

Check the three valid forms directly (String Template 4): word.isupper(), word.islower(), or word[0].isupper() and word[1:].islower(). For a single character word[1:] is empty and "".islower() is False, but a single letter is already covered by the first two checks; word.istitle() is an equivalent third check for a single word.

My Solution
#

class Solution:
    def detectCapitalUse(self, word: str) -> bool:
        return word.isupper() or word.islower() or word.istitle()

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • The third form is “first uppercase and all the rest lowercase”.

Interview Explanation
#

Only all caps, all lowercase or a capitalized first letter are valid, so I check isupper, islower and istitle. Time O(n).

Related

LeetCode 500: Keyboard Row
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 500 note: make a set for each keyboard row and keep words whose lowercase character set is a subset of one row
LeetCode 521: Longest Uncommon Subsequence I
·1 min
LeetCode Easy String
LeetCode 521 note: identical strings give -1; otherwise the longer string itself is the answer
LeetCode 434: Number of Segments in a String
·1 min
LeetCode Easy String
LeetCode 434 note: split() with no argument ignores extra spaces, so the number of pieces is the answer
LeetCode 345: Reverse Vowels of a String
·1 min
LeetCode Easy Two-Pointers String
LeetCode 345 note: the same two pointers as LC 917, with the condition switched to “is a vowel” (both cases)
LeetCode 504: Base 7
·1 min
LeetCode Easy Math String
LeetCode 504 note: repeatedly take % 7 and // 7 of the absolute value, then add the sign and reverse; handle 0 separately
LeetCode 541: Reverse String II
·1 min
LeetCode Easy Two-Pointers String
LeetCode 541 note: in every block of 2k reverse the first k; when fewer than k remain reverse them all, which slicing handles automatically