[编程题]括号匹配问题

关于括号匹配问题可以扩展出来好几个问题:

  • 传统的括号匹配,给出一个字符串,判断里面的括号是否匹配
  • 给你一个字符串,里面只包含”(“,”)”,”[“,”]”四种符号,请问你需要至少添加多少个括号才能使这些括号匹配起来。

1 传统的括号匹配

给定字符串,输出括号是否匹配,例如:

)
false
()
true
(a)
true
[]{{}}(aa)
true

解决这个问题最经典的就是用栈来实现

public class Test {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String str = "";
        while(scanner.hasNext()){
            str = scanner.nextLine();
            if ("Q".equals(str)) {
                break;
            }
            System.out.println(match(str));
        }

    }

    private static boolean match(String str) {
        Stack<Character> stack = new Stack<>();
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            try {
                switch (chars[i]) {
                case '(':
                    stack.add('(');
                    break;
                case '[':
                    stack.add('[');
                    break;
                case '{':
                    stack.add('{');
                    break;
                case ')':
                    if (stack.peek() == '(') {
                        stack.pop();
                    }
                    break;
                case ']':
                    if (stack.peek() == '[') {
                        stack.pop();
                    }
                    break;
                case '}':
                    if (stack.peek() == '{') {
                        stack.pop();
                    }
                    break;
                default:
                    break;
                }
            } catch (EmptyStackException e) {
                return false;
            }

        }

        return stack.empty();
    }
}

2

这道题转载自:http://blog.csdn.net/beiyeqingteng/article/details/7695274
给你一个字符串,里面只包含”(“,”)”,”[“,”]”四种符号,请问你需要至少添加多少个括号才能使这些括号匹配起来。
如:
[]是匹配的,所需括号个数为 0.
([])[]是匹配的, 所需括号个数为 0.
((]是不匹配的, 所需最少括号个数为 3.
([)]是不匹配的,所需最少括号个数为 2.

public static void minBrace(String s) {  

    int size = s.length();  
    // we begin with mb[1][1] 
    int[][] mb = new int[size + 1][size + 1];  
    for(int i = 1; i <= size; ++i){    
        mb[i][i] = 1;    
    }  

    // d refers to the distance between i and j, that is d = j - i 
    for(int d = 1; d < size; d++){    
        for (int i = 1; i + d <= size; i++) {  
            int j = i + d;  
            // the worst case 
            mb[i][j] = Math.min(mb[i][j - 1], mb[i + 1][j]) + 1;  
            // the case in which a char between i and j (= i + d) matches 
            // the character at position j + 1 
            for (int k = i ; k <= j - 1; k++ ) {  
                if (match(s.charAt(k - 1), s.charAt(j - 1)) == true) {                    
                    mb[i][j] = Math.min(mb[i][j], mb[i][k - 1] + mb[k + 1] [j - 1]);  
                }   
            }  
        }  
    }  
    System.out.println(mb[1][size]);    
} 

static boolean match(char a, char b){    
    if(a == '(' && b == ')')    
        return true;    
    if(a == '[' && b == ']')    
        return true;    
    return false;    
}
    原文作者:括号匹配问题
    原文地址: https://blog.csdn.net/notHeadache/article/details/52079265
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞