1. 题意
给定一系列以空格分隔开的单词,将长度大于2的单词首字母大写,其余全部小写。小于2的单词全部小写。
2. 题解
双指针分割空格,全部换做小写,再根据单词长度将首字母大写。
- 双指针
class Solution {
public:
string capitalizeTitle(string title) {
string ans(title);
int lp = 0;
int sz = title.size();
for (int i = 0;i < sz + 1; ++i) {
if (i == sz|| title[i] == ' '){
int len = i - lp;
if ( len != 1 && len != 2 ) {
ans[lp] = ans[lp] & (-33);
}
lp = i + 1;
}
else {
ans[i] = ans[i] | 32;
}
}
return ans;
}
};
根据大小写assic
码的二进制位特点,可以改成位运算。
class Solution {
public:
string capitalizeTitle(string title) {
string ans(title);
int lp = 0;
int sz = title.size();
for (int i = 0;i < sz + 1; ++i) {
if (i == sz|| title[i] == ' '){
int len = i - lp;
if ( len != 1 && len != 2 ) {
ans[lp] = toupper(ans[lp]);
}
lp = i + 1;
}
else {
ans[i] = tolower(ans[i]);
}
}
return ans;
}
};
- 迭代器版本
class Solution {
public:
string capitalizeTitle(string title) {
stringstream ss(title);
return accumulate(istream_iterator<string>(ss), {}, ""s, [](auto&& a, auto&& b) {
if (a.size()) a += " ";
ranges::transform(b, back_inserter(a), ::tolower);
if (b.size() > 2) a[a.size() - b.size()] = toupper(b[0]);
return a;
});
}
};