algoadvance

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:

  1. Input: title = "capiTalIze tHe titLe" Output: "Capitalize The Title"

  2. Input: title = "First leTTeR of EACH Word" Output: "First Letter of Each Word"

  3. Input: title = "i lOve leetcode" Output: "i Love Leetcode"

Clarifying Questions:

  1. 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.

  2. 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.

Strategy:

  1. Split the input string into words.
  2. Iterate through each word.
  3. For each word:
    • If its length is greater than 2, capitalize the first letter and lowercase the remaining letters.
    • If its length is 2 or less, convert all letters to lowercase.
  4. Join the processed words back into a single string with spaces in between.
  5. Return the resulting string.

Time Complexity:

Code:

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)

Explanation:

  1. Splitting the String: We split the input title on spaces to get individual words.
  2. Processing Words:
    • For each word, check its length.
    • If the length is greater than 2, capitalize the first letter and make the rest lowercase.
    • If the length is 2 or less, convert the entire word to lowercase.
  3. Joining Words: After processing all words, join them with spaces to form the final string.

This approach ensures that we handle each word according to its length, fulfilling the requirements of the problem.

Try our interview co-pilot at AlgoAdvance.com