问题描述
给定一个字符串,删除相邻重复字符,要求不创建新的字符串。
输入:"abbc"
输出:"abc"
输入:"cccccbbdbbaaaa"
输出:"cbdba"
C++代码
快慢指针:
#include <iostream>
using namespace std;
int main(){
char str[] = "cccccbbdbbaaaa";
int slow = 0;
int fast = 1;
while(str[slow] != '\0'){
while(fast < strlen(str) && str[slow] == str[fast]){
fast++;
}
str[++slow] = str[fast];
}
cout << str << endl;
// cout << strlen(str) << endl;
return 0;
}
代码分析
时间复杂度 O(n),遍历一遍字符串;
空间复杂度 O(1),原地更改字符串,不创建新的空间。