题目 151. 反转字符串中的单词 - 力扣(LeetCode)
class Solution {
public:// 移除多余空格void moveSpace(string& s) {// 定义快慢指针int slow = 0;int fast = 0;// 删除前导空格while (s.size() > 0 && fast < s.size() && s[fast] == ' ') {fast++;}// 删除中间空格while (fast < s.size()) {while ((fast - 1) > 0 && s[fast - 1] == s[fast] && s[fast] == ' ') {fast++;}if (fast < s.size()) {s[slow++] = s[fast++];}}// 删除尾随空格,该改变sizeif (s[slow - 1] == ' ') {s.resize(slow - 1);} else {s.resize(slow);}}void reverseWord(string& s, int left, int right) {while (left < right) {swap(s[left++], s[right--]);}}string reverseWords(string s) {moveSpace(s);// 整体反转字符串reverseWord(s, 0, s.size()-1);// 反转单词int left=0;int right=0;while(right<=s.size()){if(right==s.size()||s[right]==' '){reverseWord(s,left,right-1);left=right+1;}right++;}return s;}
};
题目55. 右旋字符串(第八期模拟笔试) (kamacoder.com)
#include<iostream>
#include<algorithm>
using namespace std;int main()
{string s;int k=0;//左旋位数//分成两个部分,整体反转,两部分分别反转cin >> k >> s;reverse(s.begin(), s.end());reverse(s.begin(), s.begin() + k);reverse(s.begin() + k, s.end());cout << s;return 0;
}
最后
要记住旋转反转单词,右旋字符串,都可以转换为先整体reverse,再局部reverse恢复,去除空格,注意resize使用,还有翻转空间