消除字符串重复字母(栈实现)

题目意思是给一个字符串aabbbassa,消除掉超过两次连续的字母,直到不能消除。

package 快手笔试;

import java.util.Scanner;
import java.util.Stack;

public class Solution1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        char[] ch = str.toCharArray();
        solve(ch);
    }

    private static void solve(char[] ch) {
        Stack<char[]> st = new Stack<>();
        for(int i = 0; i < ch.length; i++){
            char[] temp = new char[2];
            temp[0] = ch[i];
            if(st.isEmpty() || st.peek()[0] != ch[i]){
                temp[1] = '1';
                st.push(temp);
            }else{
                if(st.peek()[1] == '1'){
                    temp[1] = '2';
                    st.push(temp);
                    continue;
                }
                int index = i;
                while (ch[index] == ch[i]){
                    index++;
                    if(index == ch.length)
                        break;
                }
                i = index-1;
                st.pop();
                st.pop();
            }
        }
        Stack<Character> st2 = new Stack<>();
        while (!st.isEmpty())
            st2.push(st.pop()[0]);
        while (!st2.isEmpty())
            System.out.print(st2.pop());
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值