Yee’s Blog

Practicing Thinking Learning Sharing .

LeetCode: 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.

Solution(in C++)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        for(int index = 0; index != s.size(); ++index){
            if (s[index] == '{' || s[index] == '[' || s[index] == '(') {
                st.push(s[index]);
            } else {
                if(st.size() == 0) return false;
                if (s[index] == '}' && st.top() != '{') {
                    return false;
                } else if(s[index] == ')' && st.top() != '('){
                    return false;
                } else if(s[index] == ']' && st.top() != '['){
                    return false;
                }
                st.pop();
            }
        }
        return st.empty() ? true: false;
    }
};