← Back to LeetCode Notes

20. Valid Parentheses

easy · string · stack · solved 2026.07.30 · 10 sec read

View on LeetCode ↗
C++
class Solution {public:    bool isValid(string s) {        stack<char> character_stack{};        if (s.size() % 2 == 1) return false;        for (int i = 0; i < s.size(); i++) {            if (s[i] == '(' || s[i] == '[' || s[i] == '{') {                character_stack.push(s[i]);            } else if (s[i] == '}') {                if (character_stack.size() == 0 ||                    character_stack.top() != '{') {                    return false;                } else {                    character_stack.pop();                }            } else if (s[i] == ')') {                if (character_stack.size() == 0 ||                    character_stack.top() != '(') {                    return false;                } else {                    character_stack.pop();                }            } else if (s[i] == ']') {                if (character_stack.size() == 0 ||                    character_stack.top() != '[') {                    return false;                } else {                    character_stack.pop();                }            }        }        if (character_stack.size() != 0) return false;        return true;    }};

a little bit more lines of code than needed but simple stack problem. just push and pop chars with checking from stack.