LeetCode 151.反转字符串中的单词
链接
class Solution {
public:
string reverseWords(string s) {
removeExtraSpaces(s);
reverse(s.begin(), s.end());
for(int i = 0, j = 0; j <= s.size(); j++) {
if(s[j] == ' ' || j == s.size()) {
reverse(s.begin() + i, s.begin() + j);
i = j + 1;
}
}
return s;
}
void removeExtraSpaces(string& s) {
int slow = 0;
for(int fast = 0; fast < s.size(); fast++) {
if(s[fast] != ' ') {
if(slow != 0) {
s[slow++] = ' ';
}
while(fast < s.size() && s[fast] != ' ') {
s[slow++] = s[fast++];
}
}
}
s.resize(slow);
}
};
卡码网 55.右旋字符串
链接
#include <iostream>
#include<algorithm>
using namespace std;
int main() {
int k;
string s;
cin >> k >> s;
reverse(s.begin(), s.end());
reverse(s.begin(), s.begin() + k);
reverse(s.begin() + k, s.end());
cout << s;
return 0;
}