Given a string title
consisting of one or more words, where each word is a sequence of English alphabet letters, capitalize the string by converting:
Return the modified string.
Example:
Input: title = "capiTalIze tHe titLe"
Output: "Capitalize The Title"
Input: title = "First leTTeR of EACH Word"
Output: "First Letter of Each Word"
Input: title = "i lOve leetcode"
Output: "i Love Leetcode"
Q: Do we need to consider non-alphabetic characters or punctuation in the input string? A: No, the problem states that each word consists solely of English alphabet letters.
Q: What should we do if a word has exactly two characters? A: Convert both characters to lowercase as per the problem statement which specifies capitalizing only words longer than 2 characters.
def capitalizeTitle(title: str) -> str:
words = title.split()
processed_words = []
for word in words:
if len(word) > 2:
processed_word = word[0].upper() + word[1:].lower()
else:
processed_word = word.lower()
processed_words.append(processed_word)
return ' '.join(processed_words)
title
on spaces to get individual words.This approach ensures that we handle each word according to its length, fulfilling the requirements of the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?