使用栈检测括号是否成对出现

package stack;

import java.util.Stack;

/**
 * Created by Lanxiaowei
 * Craated on 2016/12/11 14:13
 * 检测括号是否成对出现
 * 可以将检测到左括号抽象成入栈操作,检测到右括号抽象成出栈操作,
 * 左右括号成对出现刚好可以抽象成入栈出栈操作,也就是说只要最后
 * 栈为空,则表明括号是全部成对出现的.
 */
public class Test3 {

    public static void main(String[] args) {
        String str = "())((()()()";
        //String str = "(()()()(())())";
        boolean result = judge(str);
        System.out.println(result);
    }

    public static boolean judge(String str) {
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < str.length(); i++) {
            //如果是左括号,则执行加1操作
            if (str.charAt(i) == '(') {
                stack.push('(');
            } else if (str.charAt(i) == ')') {
                //如果栈为空,则表明右括号的个数比左括号多,即括号不是成对出现的,此时直接return false.
                if(stack.isEmpty()) {
                    return false;
                }
                stack.pop();
            } else {
                throw new IllegalArgumentException("Invalid char:" + str.charAt(i));
            }
        }
        //如果最终栈为空,则表明括号是成对出现的.
        return stack.empty();
    }
}

猜你喜欢

转载自iamyida.iteye.com/blog/2344310