括号匹配 “亲兄弟”->点击消除

2024-10-09 15:56:27 浏览数 (1)

1.题目:

2.解析:这个题和括号匹配很相似,都可以用栈解决。

方法一:直接定义栈,遍历字符串,peek一下字符,是否和栈里的字符相等,相等就出栈,不相等入栈。这里注意字符输出顺序,可以再定义一个栈帮助输出:

代码:

代码语言:javascript复制
public static void main(String[] args) {
        /**
         方法一:
         */
        Scanner in = new Scanner(System.in);
        char[] s = in.next().toCharArray();

        Stack<Character> stack = new Stack<Character>();
        Stack<Character> stack2 = new Stack<Character>();//辅助stack栈数据输出顺序字符串

        for(int i = 0; i < s.length; i  ) {

            if(!stack.isEmpty() && s[i] == stack.peek()){
                stack.pop();
            }else{
                stack.push(s[i]);
            }
        }

        if(stack.isEmpty()){
            System.out.print(0);
        }

        while(!stack.isEmpty()){
            stack2.push(stack.pop());
        }
        while(!stack2.isEmpty()){
            System.out.print(stack2.pop().toString());
        }


    }

方法二:用StringBuilder模拟栈:和方法一类似

代码:

代码语言:javascript复制
/**
     方法二:用StringBuilder模拟栈:
     */
    public static void main2(String[] args){
        Scanner in = new Scanner(System.in);
        char[] s = in.next().toCharArray();

        //用StringBuilder模拟栈
        StringBuilder st = new StringBuilder();
        for(int i = 0; i < s.length; i  ) {
            char ch = s[i];
            if(st.length() != 0 && ch == st.charAt(st.length()-1)){
                //模拟出栈
                st.deleteCharAt(st.length()-1);
            }else{
                //模拟入栈
                st.append(ch);
            }
        }

        System.out.println(st.length() == 0 ? 0 : st.toString());
    }

0 人点赞