Leetcode 2129. Capitalize the Title
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:
title
? – The input string title
will contain one or more words separated by single spaces.title
is capitalized according to the given rules.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;
}
std::istringstream
to split the input title
into individual words.std::istringstream
takes care of extra spaces by default.O(n)
where n
is the length of the string.O(m)
operation where m
is the length of each word.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.
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?