代码改变世界

java 实例 判断输出的括号是否成对出现

2017-03-16 21:12  backyyan  阅读(1512)  评论(0编辑  收藏  举报

输入:

{}()
({()})
{}(
[]

输出:

true
true
false
true

代码:

import java.util.Scanner;
import java.util.Stack;
import java.util.HashMap;

class Solution {
    
    public static void main(String[] args) {
        /* Create HashMap to match opening & closing brackets */
        HashMap<Character, Character> map = new HashMap<>();
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        
        /* Test each expression for validity */
        Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {
            String expression = scan.next();
            System.out.println(isBalanced(expression, map) ? "true" : "false" );
        }
        scan.close();
    }
    
    public static boolean isBalanced(String expression, HashMap<Character, Character> map) {
        /* Odd length strings are not balanced */
        if ((expression.length() % 2) != 0) {
            return false;
        }
        
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < expression.length(); i++) {
            Character ch = expression.charAt(i);
            if (map.containsKey(ch)) {
                stack.push(ch);
            } else if (stack.isEmpty() || ch != map.get(stack.pop())) {
                return false;
            }
        }
        return stack.isEmpty();
    }
}