1. 程式人生 > >[leetcode]Valid Parentheses

[leetcode]Valid Parentheses

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

分析:

驗證括號的有效性,可以利用棧的先入後出特性。若當前字元為左括號,壓入棧中;若為右括號,若此時棧為空,返回false,不為空取棧頂元素,若為對應的左括號則為true。

class Solution {
public:
    bool isValid(string s) {     
    stack<char> st;
    for(char c : s){//遍歷字元c
        if(c == '('|| c == '{' || c == '['){
            st.push(c);
        }else{
            if(st.empty()) return false;
            else if(c == ')' && st.top() != '(') return false;
            else if(c == '}' && st.top() != '{') return false;
            else if(c == ']' && st.top() != '[') return false;
            else st.pop();
        }
    }
    return st.empty();
    }
};