leetcode 1047. Remove All Adjacent Duplicates In String(删除相邻的重复字母)

You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.

We repeatedly make duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.

Example 1:

Input: s = “abbaca”
Output: “ca”
Explanation:
For example, in “abbaca” we could remove “bb” since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is “aaca”, of which only “aa” is possible, so the final string is “ca”.

1544题如出一辙,都是删除相邻的重复字母,从左到右只删除相邻的2个。

思路:

和1544题一样,从左到右遍历,用stack保存字母,
遇到相同的字母出栈(pop),否则压栈(push)。

这里用一个数组模拟stack,更高效。

public String removeDuplicates(String s) {
    int n = s.length();
    char[] st = new char[n];
    char[] arr = s.toCharArray();
    
    int top = -1;
    
    for(char ch : arr) {
        if(top >= 0 && ch == st[top]) {
            top --;
        } else {
            st[++top] = ch; 
        }
    }
    return String.copyValueOf(st, 0, top+1); //最后一个参数是offset, 也就是substring的长度,top是0为起点的,所以要+1
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值