151.翻转字符串里的单词
注意事项
- 尽量不要一直扩充字符串,时间很慢
- 要考虑最后是否有空格的情况
class Solution {
public:
string reverseWords(string s) {
reverse(s.begin(), s.end());
int p1_start = 0, p1 = 0, p2 = 0;
while (p2 < s.size()) {
if (s[p2] == ' ')
p2++;
else {
while (p2 < s.size()) {
if (s[p2] != ' ')
s[p1++] = s[p2++];
else
break;
}
reverse(s.begin() + p1_start, s.begin() + p1);
if (p1 < s.size()) {
s[p1++] = ' ';
p1_start = p1;
}
else
p1++;
}
}
return s.substr(0, p1-1);
}
};
55.右旋转字符串
注意事项
-无
#include <iostream>
#include<algorithm>
using namespace std;
int main() {
int k;
string s;
while(cin >> k >> s) {
reverse(s.begin(), s.end());
reverse(s.begin(), s.begin()+k);
reverse(s.begin()+k, s.end());
std::cout << s << std::endl;
}
return 0;
}