20. Valid Parentheses

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.

Analysis:
这类问题用stack解决是最方便简单的。
Source Code(C++):

#include <iostream>
#include <string>
#include <stack>
#include <map>
using namespace std;

class Solution {
public:
    bool isValid(string s) {
        map<char, char> m_parentheses;
        stack<char> s_parentheses;
        m_parentheses[')'] = '(';
        m_parentheses[']'] = '[';
        m_parentheses['}'] = '{';
        for(int i=0; i<s.size(); i++) {
            if (s.at(i)=='(' || s.at(i)=='{' || s.at(i)=='[') {
                s_parentheses.push(s.at(i));
            }
            else if (s.at(i)==')' || s.at(i)=='}' || s.at(i)==']') {
                if (s_parentheses.empty()){
                    return false;
                }
                else {
                    if (s_parentheses.top() == m_parentheses[s.at(i)]){
                        s_parentheses.pop();
                    }
                    else {
                        return false;
                    }
                }   
            }
        }
        if (s_parentheses.empty()) {
            return true;
        }
        else {
            return false;
        }
    }
};

int main() {
    Solution sol;
    cout << sol.isValid("()[]{}");
    return 0;
}

你可能感兴趣的:(20. Valid Parentheses)