天天看點

棧應用—字元串括号比對問題

利用棧,可以解決一些算法問題,比如括号比對、逆波蘭表達式...

以下demo,解決括号比對問題:

BracketStr.java

/**
 * @Author: ltx
 * @Description: 棧應用-字元串括号比對問題
 */
public class BracketStr {
    private static Boolean isValid(String str) {
        //拆成char[]
        char[] chars = str.toCharArray();
        Stack<Character> left = new Stack<>();
        for (Character ch : chars) {
            //遇左括号,放入棧中
            if (ch.equals('{') || ch.equals('(') || ch.equals('[')) {
                left.push(ch);
            }
            //遇右括号,先判空,然後判斷成對,不成對的則為不比對
            if (ch.equals('}') || ch.equals(')') || ch.equals(']')) {
                //判斷棧空
                if (left.isEmpty()) {
                    return false;
                }
            }
            //判斷成對
            if (ch.equals('}')) {
                if (!left.pop().equals('{')) {
                    return false;
                }
            }
            if (ch.equals(')')) {
                if (!left.pop().equals('(')) {
                    return false;
                }
            }
            if (ch.equals(']')) {
                if (!left.pop().equals('[')) {
                    return false;
                }
            }
        }
        //判斷棧空
        if (left.isEmpty()) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
//        String str = "kh(((we)w(fwe)(456)[34][{{66555}}]56))6655";
//        String str = "sagjhsjakldgh2357465768";
//        String str = "[][]()(){}";
        String str = "we[]sd12[]23()]we(546456)dd{r6789679}";
        System.out.println(isValid(str));
    }
}
           

繼續閱讀