How to remove all adjacent duplicate characters from a string until no more can be removed in C

1 Answer

0 votes
#include <stdio.h>

char* remove_adjacent_duplicates(const char *s) {
    static char result[1024];   // static so we can return it safely
    int top = -1;               

    for (int i = 0; s[i] != '\0'; i++) {
        char ch = s[i];

        if (top >= 0 && result[top] == ch) {
            top--;              // pop
        } else {
            result[++top] = ch; // push
        }
    }

    result[top + 1] = '\0';     // null‑terminate
    
    return result;
}

int main() {
    const char *s = "abbacccada";
    
    printf("%s\n", remove_adjacent_duplicates(s));  
    
    return 0;
}


/*
run:

cada

*/

 



answered Mar 7 by avibootz

Related questions

...