java 实例 判断输出的括号是否成对出现
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 实例 判断输出的括号是否成对出现相关的知识,希望对你有一定的参考价值。
输入:
{}()
({()})
{}(
[]
输出:
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 实例 判断输出的括号是否成对出现的主要内容,如果未能解决你的问题,请参考以下文章