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.


One use case of stack.

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

bool Equals(char a, char b) {
    return (b == '{' && a == '}') || (b == '(' && a == ')') ||(b == '[' && a == ']');
}

bool isValid(string s) {
    if(s.size() % 2 != 0) return false;
    stack<char> tmp;
    for(int i = 0; i < s.size(); ++i) {
        if(s[i] == '(' || s[i] == '{' || s[i] == '[') {
            tmp.push(s[i]);
        } else {
            if(tmp.empty() || !Equals(s[i], tmp.top())) {return false;}
            else {
                tmp.pop();
            }
        }
    }
    return tmp.empty();
}

int main(void) {
    string tmp = "()[]{";
    bool res = isValid(tmp);
    cout << res << endl;
}


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