[LC] 82. Remove Adjacent Repeated Characters IV

Posted xuanlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 82. Remove Adjacent Repeated Characters IV相关的知识,希望对你有一定的参考价值。

Repeatedly remove all adjacent, repeated characters in a given string from left to right.

No adjacent characters should be identified in the final string.

Examples

  • "abbbaaccz" → "aaaccz" → "ccz" → "z"
  • "aabccdc" → "bccdc" → "bdc"
public class Solution {
  public String deDup(String input) {
    // Write your solution here
    char[] charArr = input.toCharArray();
    LinkedList<Character> stack = new LinkedList<>();
    for (int i = 0; i < charArr.length; i++) {
      char cur = charArr[i];
      if (!stack.isEmpty() && stack.peekFirst() == cur) {
        while (i + 1 < charArr.length && charArr[i] == charArr[i + 1]) {
          i += 1;
        }
        stack.pollFirst();
      } else {
        stack.offerFirst(cur);
      }
    }
    char[] res = new char[stack.size()];
    for (int i = res.length - 1; i >= 0; i--) {
      res[i] = stack.pollFirst();
    }
    return new String(res);
  }
}

 

以上是关于[LC] 82. Remove Adjacent Repeated Characters IV的主要内容,如果未能解决你的问题,请参考以下文章

LF.82.Remove Adjacent Repeated Characters IV

LC.203. Remove Linked List Elements

C. Remove Adjacent

LF.79.Remove Adjacent Repeated Characters I

LeetCode 1209. Remove All Adjacent Duplicates in String II

1047. Remove All Adjacent Duplicates In String