Capitalize the Title — LeetCode 2129 Python Solution
- Problem
- #2129
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: If the length of the word is 1 or 2 letters, change all letters to lowercase.
Example
- Input
- title = "capiTalIze tHe titLe"
- Output
- "Capitalize The Title"
- Explanation
- Since all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.
Python solution
class Solution:
def capitalizeTitle(self, title: str) -> str:
words = [w.lower() if len(w) < 3 else w.capitalize() for w in title.split()]
return " ".join(words)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the length of the string `title` auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2129. Capitalize the Title is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2129. Capitalize the Title?
- LeetCode 2129. Capitalize the Title is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2129. Capitalize the Title?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2129. Capitalize the Title?
- The Python solution on this page uses O(n), where n is the length of the string `title` auxiliary space.
- What topics does LeetCode 2129. Capitalize the Title cover?
- LeetCode 2129. Capitalize the Title is tagged String on LeetCode.