利用快慢指针,慢指针为新数组下标,快指针遍历原数组找到需要的元素然后赋值给慢指针所指的值。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slow = 0, fast = 0;
for (fast = 0; fast < nums.size(); fast++) {
if (nums[fast] != val)
nums[slow++] = nums[fast];
}
return slow;
}
};
清除多余的空格利用到了上个题的思想
class Solution {
public:
string reverseWords(string s) {
// 1.去除多余空格
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);
// 2.翻转整个字符串
reverse(s.begin(), s.end());
// 3.翻转每个单词
int start = 0;
for (int i = 0; i <= s.size(); ++i) {
if (i == s.size() || s[i] == ' ') {
reverse(&s[start], &s[i]);
start = i + 1;
}
}
return s;
}
};
整体反转+局部反转
#include <bits/stdc++.h>
using namespace std;
int main() {
int k;
string s = "";
cin >> k;
cin >> s;
reverse(s.begin(), s.end());
reverse(s.begin(), s.begin() + k);
reverse(s.begin() + k, s.end());
cout << s;
}