题解 | #点击消除#

点击消除

https://www.nowcoder.com/practice/8d3643ec29654cf8908b5cf3a0479fd5

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String s = in.next();
        Stack<Character> st = new Stack<>();
        for (int i=0;i<s.length();i++) { 
            char a = s.charAt(i);//取出第i个元素
            if(st.isEmpty()||a!=st.peek()){//如果栈是空的或者第i个数据不是栈顶的数据
                st.push(a);//就将数据压入栈中
            }else if(a==st.peek()){//如果栈顶的数据为第i个元素的数据
                st.pop();//就将栈顶的数据弹出
            }
        }
        if(st.isEmpty()){
            System.out.println(0);//如果栈是空的,就直接输出0
        }else{
            Stack<Character>st2= new Stack<>();
            while(!st.isEmpty()){
                st2.push(st.pop());
            }
            while(!st2.isEmpty()){
                System.out.print(st2.pop());
            }
        }//注意放入栈中的数据弹出是反着的,所以要再次放入另一个栈中,这样才是正的
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
哥_留个offer先:跟他说,你这个最好用c#,微软就用c#Java不适合这个项目
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务