题目
代码(7.28 首刷看解析)
class Solution {
public:
string reverseWords(string s) {
int n = s.size();
reverse(s.begin(), s.end());
int i = 0;
int idx = 0;
while(i < n) {
// 填一个空白字符然后将idx移动到下一个单词的开头位置
if(s[i] != ' ') {
if(idx != 0) s[idx++] = ' ';
}
// 循环遍历至单词的末尾
int end = i;
while(end < n && s[end] != ' ') s[idx++] = s[end++];
// 反转整个单词
reverse(s.begin()+idx-(end-i), s.begin()+idx);
// 更新i,去找下一个单词
i = end;
i++;
}
s.erase(s.begin()+idx, s.end());
return s;
}
};
代码(8.28 二刷自解)
牛客一道类似的题目:BM83 字符串变形
#include <string>
class Solution {
public:
string trans(string s, int n) {
vector<string> q;
int i = 0;
int begin = 0;
while(i < n) {
begin = i;
while(begin <= n && s[begin++] != ' '); // 找到空格
string str = s.substr(i, begin-i-1);
q.emplace_back(str);
i = begin;
}
// 大小写转换
for(string& str : q) {
for(char& c : str) {
if(c >= 'a' && c <= 'z')
c -= 32;
else c += 32;
}
}
string ans;
while(!q.empty()) {
string str = q.back();
q.pop_back();
ans += str;
ans += " ";
}
ans.pop_back();
if(s.back() == ' ')
ans.insert(ans.begin(), ' ');
return ans;
}
};
代码(9.5 三刷自解)
class Solution {
public:
string reverseWords(string s) {
int i = 0;
while(s[i] == ' ') i++;
s = s.substr(i);
reverse(s.begin(), s.end());
i = 0;
while(s[i] == ' ') i++;
string ans;
while(i < s.size()) {
if(s[i] != ' ') {
string tmp;
while(i < s.size() && s[i] != ' ') tmp += s[i++];
reverse(tmp.begin(), tmp.end());
ans += tmp + " ";
} else {
i++;
}
}
ans.pop_back();
return ans;
}
};