algoadvance

Leetcode 2129. Capitalize the Title

Problem Statement

You are given a string title consisting of one or more words separated by a single space, with each word containing English letters. Your task is to capitalize each word such that:

  1. If the length of the word is exactly 1 character, it remains lowercase.
  2. If the length of the word is exactly 2 characters, it remains lowercase.
  3. If the length of the word is more than 2 characters, capitalize the first character and convert the rest to lowercase.

Clarifying Questions

  1. Input:
    • What is the format of title? – The input string title will contain one or more words separated by single spaces.
  2. Output:
    • What is the format of the output? – A single string where each word in the title is capitalized according to the given rules.

Code

Here is the C++ solution for the problem:

#include <iostream>
#include <sstream>
#include <cctype>

std::string capitalizeTitle(std::string title) {
    std::istringstream iss(title);
    std::string result;
    std::string word;
    
    while (iss >> word) {
        if (word.length() > 2) {
            word[0] = std::toupper(word[0]);
            for (size_t i = 1; i < word.length(); ++i) {
                word[i] = std::tolower(word[i]);
            }
        } else {
            for (char &c : word) {
                c = std::tolower(c);
            }
        }
        
        if (!result.empty()) {
            result += " ";
        }
        result += word;
    }
    
    return result;
}

int main() {
    std::string title = "this is a test title for Capitalize the Title";
    std::string capitalizedTitle = capitalizeTitle(title);

    std::cout << capitalizedTitle << std::endl;

    return 0;
}

Strategy

  1. Reading Words: Use std::istringstream to split the input title into individual words.
  2. Capitalizing Words: For each word:
    • If its length is greater than 2, capitalize the first character and convert the remaining characters to lowercase.
    • If its length is 2 or less, convert all characters to lowercase.
  3. Constructing the Result: Append each processed word to the result string with spaces in between.
  4. Edge Cases: Handle cases where the input string is empty or contains multiple spaces. The std::istringstream takes care of extra spaces by default.

Time Complexity

Combining both, the overall time complexity is O(n), which is efficient for this problem as each character in the input string is processed a constant number of times.

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