Member-only story

Leetcode 2129: Capitalize the Title

Pierre-Marie Poitevin
3 min readJan 9, 2022

--

Today, we are changing the uppercase and lowercase of characters in order to capitalize a title. The capitalization is the same as a regular capitalization, except that words of 1 and 2 letters a set to lowercase, without capitalization. This is the problem statement.

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.Otherwise, change the first letter to uppercase and the remaining letters to lowercase.

Return the capitalized title.

We are also given a few examples to work with:

Examples and constraints

To solve the problem, I opted to traverse the String and capitalize every time I encountered a new word. This is easily done, by switching the first letter of the string to uppercase and by doing the same after each empty space character.

Now, I needed to handle the 1 and 2 letter words too. I did that by marking the index each time I was changing a character to uppercase (or at the beginning of each word). Then when I encounter an empty space, or the end of the String, I can check at what index the word started. If the word started only 1 or 2…

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet