Skip to content

Commit c46acca

Browse files
添加 1047.删除字符串中的所有相邻重复项.md C语言版本
1 parent c249f3a commit c46acca

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

problems/1047.删除字符串中的所有相邻重复项.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,57 @@ var removeDuplicates = function(s) {
269269
};
270270
```
271271

272+
C:
273+
方法一:使用栈
274+
```c
275+
char * removeDuplicates(char * s){
276+
//求出字符串长度
277+
int strLength = strlen(s);
278+
//开辟栈空间。栈空间长度应为字符串长度+1(为了存放字符串结束标志'\0')
279+
char* stack = (char*)malloc(sizeof(char) * strLength + 1);
280+
int stackTop = 0;
281+
282+
int index = 0;
283+
//遍历整个字符串
284+
while(index < strLength) {
285+
//取出当前index对应字母,之后index+1
286+
char letter = s[index++];
287+
//若栈中有元素,且栈顶字母等于当前字母(两字母相邻)。将栈顶元素弹出
288+
if(stackTop > 0 && letter == stack[stackTop - 1])
289+
stackTop--;
290+
//否则将字母入栈
291+
else
292+
stack[stackTop++] = letter;
293+
}
294+
//存放字符串结束标志'\0'
295+
stack[stackTop] = '\0';
296+
//返回栈本身作为字符串
297+
return stack;
298+
}
299+
```
300+
方法二:双指针法
301+
```c
302+
char * removeDuplicates(char * s){
303+
//创建快慢指针
304+
int fast = 0;
305+
int slow = 0;
306+
//求出字符串长度
307+
int strLength = strlen(s);
308+
//遍历字符串
309+
while(fast < strLength) {
310+
//将当前slow指向字符改为fast指向字符。fast指针+1
311+
char letter = s[slow] = s[fast++];
312+
//若慢指针大于0,且慢指针指向元素等于字符串中前一位元素,删除慢指针指向当前元素
313+
if(slow > 0 && letter == s[slow - 1])
314+
slow--;
315+
else
316+
slow++;
317+
}
318+
//在字符串结束加入字符串结束标志'\0'
319+
s[slow] = 0;
320+
return s;
321+
}
322+
```
272323

273324

274325
-----------------------

0 commit comments

Comments
 (0)