码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-03-16 22:14:19      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:res   main   new   代码   key   har   test   div   i++   

输入:

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

输出:

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();
    }
}

 

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

标签:res   main   new   代码   key   har   test   div   i++   

原文地址:http://www.cnblogs.com/Angella/p/6561640.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!