删除连续重复字符

字符串删除掉连续的3个重复的字符。比如“abbbc”,返回“ac”,"abbbaac",返回“c”

题解,可以利用栈来实现,创建一个对象用来储存,字母以及字母的个数,最后从栈中取出元素,拼接到字符串

package 算法.栈;

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
//        remove(str);
        System.out.println(remove(str));
    }

    public static String remove(String str) {
        Stack<Object> stack = new Stack<>();
        int n = str.length();
        for (int i = 0; i < n; i++) {//顺序处理每个字符
            char c = str.charAt(i);

            //栈为空
            if (stack.isEmpty()) {
                stack.push(new CharWithCount(c, 1));
                continue;
            }

            //栈不为空,栈顶字符跟c比较,如果不相同
            CharWithCount topChar = (CharWithCount) stack.peek();
            if (topChar.c != c) {
                stack.push(new CharWithCount(c, 1));
                continue;
            }
            //栈顶字符跟c相同,判断栈顶字符的计数是否达到3,如果达到,则出栈,否则计数+1
            if (topChar.count == 2) {
                stack.pop();
                continue;
            }
            //栈顶元素跟c相同,并且满足连连消
            topChar.count++;
        }
        
        String up = "";
        for (int i = 0; i < stack.size(); i++) {
            CharWithCount a = (CharWithCount) stack.get(i);
            up += a.c;
        }
        return up;
    }

    public static class CharWithCount {
        public char c;
        public int count;

        public CharWithCount(char c, int count) {
            this.c = c;
            this.count = count;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值