一、题目描述
二、思路
三、解题过程
-
计算长度并开辟栈
- 栈的长度需加一,因为要放 '\0 '
int sLen = strlen(s);
char* res = (char*)malloc(sizeof(char) * (sLen + 1));
-
遍历字符串并操作栈
int top = 0;
int index = 0;
while(index < sLen){
if(top == 0 || res[top - 1] != s[index]){
res[top++] = s[index++];
}else{
top--;
index++;
}
}
-
在输出字符串末尾加上'\0'并返回输出字符串
res[top] = '\0';
return res;
四、代码
char * removeDuplicates(char * s){
int sLen = strlen(s);
char* res = (char*)malloc(sizeof(char) * (sLen + 1));
int top = 0;
int index = 0;
while(index < sLen){
if(top == 0 || res[top - 1] != s[index]){
res[top++] = s[index++];
}else{
top--;
index++;
}
}
res[top] = '\0';
return res;
}
时间复杂度:O(n),空间复杂度:O(n)。