1. 程式人生 > >20. Valid Parentheses括號匹配

20. Valid Parentheses括號匹配

ase action style spa break ive clas not str


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.

自己代碼:

class Solution {
public:
    bool isValid(string
s) { stack<char> parent; for(char c:s){ if(c ==[||c == ( || c == {) parent.push(c); //左括號進棧 else if(parent.empty()) return false; else{ //有右括號且與棧頂匹配,則棧頂元素出棧 if(c ==] && parent.top() ==
[) parent.pop(); else if(c ==} && parent.top() == {) parent.pop(); else if(c ==) && parent.top() == () parent.pop(); else return false; } } if(parent.empty()) return true; else return false; } };

巧妙的方法,discussion區發現:

遇到左括號,則使對應右括號進棧,例如:遇到“{”,進棧“}”。遇到“[”,進棧“]”。遇到“(”,進棧“)”。

非右括號,則看它是否與棧頂元素相等,相等即匹配。

public boolean isValid(String s) {
    Stack<Character> stack = new Stack<Character>();
    for (char c : s.toCharArray()) {
        if (c == ‘(‘)                                 //遇到左右括號,使括號進棧
            stack.push(‘)‘);
        else if (c == ‘{‘)
            stack.push(‘}‘);
        else if (c == ‘[‘)
            stack.push(‘]‘);
        else if (stack.isEmpty() || stack.pop() != c)  //遇到非右括號,若棧空,返回false。否則彈出棧頂元素,看其是否與當前元素相等,否則錯誤
            return false;
    }
    return stack.isEmpty();
}

用switch語句寫:

 bool isValid(string s) {
        stack<char> paren;
        for (char& c : s) {
            switch (c) {
                case (: 
                case {: 
                case [: paren.push(c); break;
                case ): if (paren.empty() || paren.top()!=() return false; else paren.pop(); break;
                case }: if (paren.empty() || paren.top()!={) return false; else paren.pop(); break;
                case ]: if (paren.empty() || paren.top()!=[) return false; else paren.pop(); break;
                default: ; // pass
            }
        }
        return paren.empty() ;
    }

20. Valid Parentheses括號匹配