LaiCode 82. Remove Adjacent Repeated Characters IV

LaiCode 82. Remove Adjacent Repeated Characters IV

题目

在这里插入图片描述

思路

  1. First, we need a stack to store elements which need to be in the output.
  2. Then we need to put the string into a character array, and traverse the whole array. In the meanwhile, we need to put unique element in to the stack and to check each element if it is the same as the top element of the stack.
  3. If the element is different from the top element of the stack, then we should push it into the stack; And if the element is the same as the top element of the stack, we move the pointer to the next element, until we find the different one or we reach the end of the array.
  4. Finally, we need an another array to put the elements in the stack into it, and construct a string with the array.

代码

public class Solution {
  public String deDup(String input) {
    // Write your solution here
    // Corner case
    if (input == null || input.length() <= 1) {
      return input;
    }

    char[] str = input.toCharArray();
    Deque<Character> stack = new ArrayDeque<>();
    for (int i = 0; i < str.length; ) {
      char curChar = str[i];
      if (!stack.isEmpty() && stack.peekFirst() == curChar) {
        while (i < str.length && str[i] == curChar) {
          i++;
        }
        stack.pollFirst();
      } else {
        stack.offerFirst(str[i++]);
      }
    }

    // Post processing
    int len = stack.size();
    int[] ans = new int[len];
    for (int i = len - 1; i >= 0; i--) {
      ans[i] = stack.pollFirst();
    }
    return new String(ans, 0, len);
  }
}

分析

The time complexity is O(n), and the n is the length of the input.
The space complexity is O(n), because it need an character array, a stack and a post processing array.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值