Similar Problems
Similar Problems not available
Capitalize The Title - Leetcode Solution
Companies:
LeetCode: Capitalize The Title Leetcode Solution
Difficulty: Easy
Topics: string
The Capitalize the Title problem on LeetCode is a relatively simple problem that involves modifying a string by capitalizing the first letter of each word. The problem statement is as follows:
Given a string s, capitalize the first letter of each word and return the modified string.
Example 1:
Input: s = "hello world"
Output: "Hello World"
Example 2:
Input: s = "a short sentence"
Output: "A Short Sentence"
Constraints:
- 1 <= s.length <= 10^5
- s consists of lowercase English letters, spaces, and/or punctuation.
To solve this problem, we will need to iterate through the string and modify each word to capitalize the first letter. Here's one possible implementation in Python:
class Solution:
def capitalize(self, s: str) -> str:
# Split the string into a list of words
words = s.split()
# Capitalize the first letter of each word
capitalized = [word[0].upper() + word[1:] for word in words]
# Join the capitalized words back into a string
return ' '.join(capitalized)
Let's go through each step of the implementation:
-
We first split the input string into a list of words using the
split()
method. This splits the string at every space and returns a list of words. -
We then iterate through the list of words using a list comprehension. For each word, we use string slicing to extract the first letter (
word[0]
) and convert it to uppercase (upper()
), and then concatenate it with the rest of the word (word[1:]
) using string slicing. -
We then join the capitalized words back into a string using the
join()
method. This method takes a list of strings and returns a single string with each element joined by a specified delimiter. -
Finally, we return the capitalized string.
This implementation should correctly solve the problem for all test cases.
Capitalize The Title Solution Code
1