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.

輸入一個字符串s,這個字符串是由字符'(', ')', '{', '}', '[' 和 ']'組成的。咱們須要斷定這個字符串的格式是否有效。斷定是否有效的一句就是,字符必須嚴格有序。例如"()" 和 "()[]{}"是有效的,可是"()"和"()[]{}"就是無效的。數據結構

想法

  • 這道題目比較適合用棧做爲存儲中間結果的數據結構,由於字符應當是後進先出,方便咱們進行判斷。
  • 對於前一半字符(eg.‘(’,'[','{'),咱們對它們進行入棧操做。
  • 若是遇到了後半字符,咱們須要對棧頂元素取出,並判斷棧頂字符和當前字符是否匹配。若是不匹配,即整個字符串無效。
  • 當整個字符串的遍歷結束的時候,判斷棧是否爲空(徹底匹配)。

解法

Stack<Character> save = new Stack<Character>();
        if(s.length() == 0)return true;
        
        for(char c : s.toCharArray()){
            if(c == '('){
                save.push(')');
            }else if (c == '['){
                save.push(']');
            }else if (c == '{'){
                save.push('}');
            }else if (save.isEmpty() || c != save.pop()){
                return false;
            }
        }
        
        return save.isEmpty();
相關文章
相關標籤/搜索