2129. Capitalize the Title#
You are given a string title
, which consists of one or more words separated by a single space. Each word contains only English letters. You are required to capitalize the first letter of each word according to the following rules:
- If the word has a length of
1
or2
, all letters should be converted to lowercase. - Otherwise, capitalize the first letter of the word and convert the remaining letters to lowercase.
Return the title
after capitalization.
Example 1:
Input: title = "capiTalIze tHe titLe"
Output: "Capitalize The Title"
Explanation: Since all the words have a length of at least 3, we capitalize the first letter of each word and convert the remaining letters to lowercase.
Example 2:
Input: title = "First leTTeR of EACH Word"
Output: "First Letter of Each Word"
Explanation: The word "of" has a length of 2, so it remains completely lowercase. The other words have a length of at least 3, so we capitalize the first letter of each word and convert the remaining letters to lowercase.
Example 3:
Input: title = "i lOve leetcode"
Output: "i Love Leetcode"
Explanation: The word "i" has a length of 1, so it remains lowercase. The other words have a length of at least 3, so we capitalize the first letter of each word and convert the remaining letters to lowercase.
Note:
title
consists of words separated by a single space, and does not contain any leading or trailing spaces.- Each word consists of uppercase and lowercase English letters, and is non-empty.
Simulation#
class Solution {
public:
string capitalizeTitle(string title) {
for (int i = 0; i < title.size(); ++i) {
int cnt = 0;
for (int j = i; title[j] != ' '; ++j) {
++cnt;
if (j + 1 >= title.size()) {
conversion(title, cnt, i, i + cnt);
break;
}
}
conversion(title, cnt, i, i + cnt);
i += cnt;
}
return title;
}
// str sentence, cnt word length, i word starting index, j word ending index
void conversion(string &str, int cnt, int i, int j) {
if (cnt <= 2) {
for (int k = i; k < j; ++k) {
str[k] |= 32;
// str[k] = tolower(str[k]);
}
} else {
str[i] &= 95;
// str[i] = toupper(str[i]);
for (int k = i + 1; k < j; ++k) {
str[k] |= 32;
// str[k] = tolower(str[k]);
}
}
}
};
Simplified
class Solution {
public:
string capitalizeTitle(string title) {
for (int i = 0; i < title.size(); ++i) {
int j = i;
for (; title[j] != ' ' && j < title.size(); ++j) {
}
if (j - i > 2) {
title[i++] &= 95;
}
while (i < j) {
title[i++] |= 32;
}
}
return title;
}
};