题解 | 点击消除

点击消除

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);
        String s = in.nextLine();
        Stack<Character> st = new Stack<>();
        for(int i=s.length()-1;i>=0;--i){
            Character c = s.charAt(i);
            if(st.empty()){
                st.add(c);
            }else{
                Character top = st.peek();//查看栈顶,与下面2句相同作用,但是性能理论上会更好
                //Character top = st.pop();
                //st.add(top);
                if(top==c){
                    st.pop();
                }else{
                    st.add(c);
                }
            }
        }

        if(st.empty()){     
            System.out.print(0);
            return ;
        }            
        while(!st.empty()){
            System.out.print(st.pop());
        }  
    }
}

利用char[]手写一个简单的栈其实不难,这里应该手写栈的几个基础功能的,性能会更高。比如排名第一的题解:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Stack;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = br.readLine();
        int len = str.length();
        int index = -1;
        char[] chs = new char[len+1];
        for(int i = 0; i < len; i++){
            if(index != -1 && chs[index] == str.charAt(i)){
                index--;
            }
            else{
                chs[++index] = str.charAt(i);
            }
        }
        if(index == -1){
            System.out.println(0);
        }
        String res = new String(chs, 0, index + 1);
        System.out.println(res);
    }
}

全部评论

相关推荐

01-11 08:47
门头沟学院 Java
choumoduji...:读研的目的就是为了以最快的速度和最低的要求完成“学校”规定的毕业标准,而不是所谓课题组的要求
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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