小白筆記--------------------------leetcode(20. Valid Parentheses )

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.


這道題用到了棧,遍歷字符串,將所有左括號壓入棧中,這裏有個重要的點,那就是右括號總是與離他最近的左括號配對,

所以接下來找到右括號之後,直接查詢棧頂,如果配對則推出,不配對則不做操作,最後判斷棧是否爲空,也就是全部配對

成功,來判斷最終結果。

代碼:

public class Solution {
    public boolean isValid(String s) {
        boolean result = true;
        if(s.length() % 2 != 0){
            return false;
        }
        Stack a = new Stack();
        char[] b = s.toCharArray();
        for(int i = 0; i < s.length();i++){//全部壓入棧中
            if(b[i] == '(' || b[i] == '{' || b[i] == '['){
                a.push(b[i]);
            }
            if(b[i] == ')' || b[i] == '}' || b[i] == ']' ){
                if(a.empty()){
                    result = false;
                }else{
                    if(((char)a.peek() + 1 == b[i]) || ((char)a.peek() + 2 == b[i])){
                        a.pop();
                    }
                }
            }
        }
        if(a.empty()){
            result = true;
        }else{
            result = false;
        }
          
        return result;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章