Capitalize the Title Problem
#2129
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2129.
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
1or2letters, change all letters to lowercase. - Otherwise, change the first letter to uppercase and the remaining letters to lowercase.
Return the capitalized title.
Example 1:
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.
Example 2:
Input: title = "First leTTeR of EACH Word"
Output: "First Letter of Each Word"
Explanation:
The word "of" has length 2, so it is all lowercase.
The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.
Example 3:
Input: title = "i lOve leetcode"
Output: "i Love Leetcode"
Explanation:
The word "i" has length 1, so it is lowercase.
The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.
Constraints:
1 <= title.length <= 100titleconsists of words separated by a single space without any leading or trailing spaces.- Each word consists of uppercase and lowercase English letters and is non-empty.
Solution
Approach: Simulation
Split the title into words. A word with one or two letters becomes all lower case; any other word gets an upper case first letter and the rest in lower case. Join the words with single spaces.
Complexity: time O(n); space O(n).
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)