Iterate through characters in a string and remove consecutive duplicates

a1a*_*1a1 2 java string algorithm replace duplicates

I am trying to iterate through a string and remove consecutive duplicates letter.

ABBACBAABCB-->AACBAABCB-->CBAABCB-->CBBCB-->CCB-->B
Run Code Online (Sandbox Code Playgroud)

My Idea was to iterate through the string and remove duplicates inside a do-while loop.

My code:

ABBACBAABCB-->AACBAABCB-->CBAABCB-->CBBCB-->CCB-->B
Run Code Online (Sandbox Code Playgroud)

Obviously this doesn't work, it simply loop forever.

From what I have gathered you can't do list = results on java as string are immutable.

How can this be done with Java?

sak*_*029 5

您应该使用这样的堆栈。

static String removeConsecutiveDupplicatesLetter(String s) {
    Stack<Character> stack = new Stack<>();
    for (char c : s.toCharArray())
        if (!stack.isEmpty() && stack.peek() == c)
            stack.pop();
        else
            stack.push(c);
    return stack.stream().map(String::valueOf).collect(Collectors.joining());
}
Run Code Online (Sandbox Code Playgroud)

String s = "ABBACBAABCB";
System.out.println(removeConsecutiveDupplicatesLetter(s));
Run Code Online (Sandbox Code Playgroud)

结果:

B
Run Code Online (Sandbox Code Playgroud)

这就像这样。

stack    c
-------  -
[]       A 
[A]      B
[A B]    B
[A]      A
[]       C
[C]      B
[C B]    A
[C B A]  A
[C B]    B
[C]      C
[]       B
[B]
Run Code Online (Sandbox Code Playgroud)

您也可以char[]用作堆栈而不是Stack.

static String removeConsecutiveDupplicatesLetter(String s) {
    int length = s.length();
    char[] stack = new char[length];
    int index = 0;
    for (char c : s.toCharArray())
        if (index > 0 && stack[index - 1] == c)
            --index;
        else
            stack[index++] = c;
    return new String(stack, 0, index);
}
Run Code Online (Sandbox Code Playgroud)