码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 82. Remove Adjacent Repeated Characters IV

时间:2020-02-19 13:15:33      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:offer   length   ++   ack   stack   cdc   empty   res   har   

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

标签:offer   length   ++   ack   stack   cdc   empty   res   har   

原文地址:https://www.cnblogs.com/xuanlu/p/12330552.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!