题解 | 括号配对问题

括号配对问题

https://www.nowcoder.com/practice/57260c08eaa44feababd05b328b897d7

import java.util.Scanner;  

import java.util.Stack;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String st = in.nextLine();
        Stack<Character> stack = new Stack<>();
        boolean flag = false;

        for(Character c:st.toCharArray()){
            if(c == '[' || c == '('){
                stack.push(c);
            }else if(!stack.isEmpty()&& stack.peek() =='[' && c == ']'){
                stack.pop();
            }else if(!stack.isEmpty()&& stack.peek() =='(' && c == ')'){
                stack.pop();
            }else if(c == ')' || c == ']'){
                stack.push(c);
            }
            }
        System.out.println(stack.isEmpty() ? "true" : "false"); 
    }    
}   


    

经典括号匹配问题,利用Stack存储和取出新接收到的指定字符,并和后续紧跟着的指定字符做配对且决定是否配对成功

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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