题解 | 括号配对问题

括号配对问题

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

import java.util.Scanner; 

import java.util.ArrayList;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String st = in.nextLine();
        StringBuilder input = new StringBuilder(st);
        ArrayList fuhao = new ArrayList();
        for(int i = 0; i < input.length();i++){
            char c = input.charAt(i);
            if(c == '(' || c == ')'||c == '['||c == ']'){
                caozuo(fuhao,c);
            }
        }
        if(fuhao.size() == 0){
            System.out.print(true);
        }else{
            System.out.print(false);
        }
        
        
    }
    public static void caozuo(ArrayList fuhao,char c){
        if(fuhao.size() != 0){
            if(c == ')' && fuhao.get(fuhao.size()-1).equals('(')){
            fuhao.remove(fuhao.size()-1);
        }else if(c == ']' && fuhao.get(fuhao.size()-1).equals('[')){
            fuhao.remove(fuhao.size()-1);
        }else {
            fuhao.add(c);
        }
        }else{
            fuhao.add(c);
        }
        
        
    }

    
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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