algoadvance

Leetcode 2129. Capitalize the Title

Problem Statement

You are given a string title which consists of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by following the rules below:

Clarifying Questions

  1. Are there any non-alphabetic characters in the input string?
    • No, the input string consists only of English letters and spaces.
  2. Can the input string be empty?
    • Yes, we need to handle the case where the input string is empty.
  3. Should leading or trailing whitespaces be removed?
    • The input string does not contain leading or trailing whitespaces according to the problem description.
  4. What about words with exactly two letters?
    • Words with exactly two letters should be converted to lowercase.

Code

public class Solution {
    public String capitalizeTitle(String title) {
        // Split the input title into words
        String[] words = title.split(" ");
        StringBuilder result = new StringBuilder();

        // Iterate through each word
        for (String word : words) {
            if (word.length() > 2) {
                // Capitalize first letter and set rest to lowercase
                result.append(Character.toUpperCase(word.charAt(0)))
                      .append(word.substring(1).toLowerCase());
            } else {
                // Convert entire word to lowercase
                result.append(word.toLowerCase());
            }
            // Append a space after each word
            result.append(" ");
        }

        // Trim the trailing space and return the result
        return result.toString().trim();
    }
}

Strategy

  1. Splitting the Input: We first split the input string by spaces to get individual words.
  2. Processing Each Word:
    • If the word length is greater than 2, capitalize the first letter and make the rest lowercase.
    • If the word length is 2 or less, convert the entire word to lowercase.
  3. Concatenation:
    • Append each processed word to a StringBuilder.
    • Append a space after each word.
  4. Trimming the Result: After processing all words, trim the trailing space to produce the correct output format.

Time Complexity

This approach ensures that we handle all the given requirements within optimal time complexity.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI