Remove Pair of Consecutive Duplicate Characters

Pair of Consecutive Duplicate Characters are strings that have the same character after another such as aabbccdd.

String like abccba is also pair of consecutive duplicate characters, if cc is removed, now bb has become a pair, after removing it, aa becomes pair.

String madam is not pair of consecutive duplicate characters because d doesn't have consecutive duplicate characters.

package org.wesome.dsalgo;

import java.util.Stack;

public class DuplicateCharacters {
    public static String duplicateCharacters(String str) {
        Stack<Character> stack = new Stack<>();
        for (char c : str.toCharArray()) {
            if (!stack.empty() && c == stack.peek()) {
                stack.pop();
            } else {
                stack.push(c);
            }
        }
        return stack.toString();
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class DuplicateCharactersTest {
    @Test
    void duplicateCharactersTest1() {
        String duplicateCharacters = "wesomeemosew";
        Assertions.assertEquals("[]", DuplicateCharacters.duplicateCharacters(duplicateCharacters));
    }

    @Test
    void duplicateCharactersTest2() {
        String duplicateCharacters = "abcddcba";
        Assertions.assertEquals("[]", DuplicateCharacters.duplicateCharacters(duplicateCharacters));
    }

    @Test
    void duplicateCharactersTest3() {
        String duplicateCharacters = "madam";
        Assertions.assertEquals("[m, a, d, a, m]", DuplicateCharacters.duplicateCharacters(duplicateCharacters));
    }
}

 

follow us on