java--括号匹配

2014 华为校园招聘机试题——-编程:

题目:给定一组括号如“[ { ( [ ] ) ( ) } ]” ,括号匹配正确,如“[ { ] }”,括号匹配错误,任意给定一组括号,得出其是否匹配。

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

public class Bracket {
	boolean isMatched(String brackets) {
		int string_size = brackets.length();
		Stack<Character> match = new Stack<Character>();
		char symbol;
		boolean is_match = true;
		for (int i = 0; i < string_size; i++) {
			symbol = brackets.charAt(i);
			if (symbol == '{' || symbol == '[' || symbol == '(')
				match.push(symbol);
			if (symbol == '}' || symbol == ']' || symbol == ')') {
				if (match.isEmpty()) {
					is_match = false;
					break;
				} else {
					if ((symbol == '}' && match.peek() == '{')
							|| (symbol == ']' && match.peek() == '[')
							|| (symbol == ')' && match.peek() == '('))
						match.pop();
					else {
						is_match = false;
						break;
					}
				}
			}
		}
		if (!match.empty())
			is_match = false;
		return is_match;
	}

	public static void main(String[] args) {
		Bracket B = new Bracket();
		Scanner input = new Scanner(System.in);
		String test_string = input.nextLine();
		if (B.isMatched(test_string))
			System.out.println("Successful match");
		else
			System.out.println("Failed match");
	}
}

    原文作者:括号匹配问题
    原文地址: https://blog.csdn.net/ftxc_blog/article/details/12688247
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞