Problem:
https://leetcode.com/problems/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.
Thought:
traverse the string, when meet ' ( ' ,' [ ' ,' { ' push it into stack, when meet ' ) ', ' } ' , ' ] ' , pop stack ,campare if they meet each other, if failes ,return false.
if stack is not empty after, return false.
otherwise, return true
Code C++:
class Solution { public: bool isValid(string s) { if (s.length() % 2) { return false; } vector<char> stack; stack.push_back(s[0]); for (int i = 1; i < s.length(); i++) { if (s[i] == '[' || s[i] == '{' || s[i] == '(') stack.push_back(s[i]); else if (s[i] == '}'){ char c = stack.back(); stack.pop_back(); if (c != '{') return false; } else if (s[i] == ']'){ char c = stack.back(); stack.pop_back(); if (c != '[') return false; } else if (s[i] == ')'){ char c = stack.back(); stack.pop_back(); if (c != '(') return false; } else return false; } if (stack.size() > 0) return false; return true; } };