20 Valid Parentheses
bool isOpening(char i) {
return (i == '[' || i == '(' || i == '{');
}
// need explicitly b/c i need to ignore other nonsense chars
bool isClosing(char i) {
return (i == ']' || i == ')' || i == '}');
}
bool isValid(string s) {
stack<char> st;
unordered_map<char, char> brackets = {
{ ']' , '[' },{ ')' , '(' },{ '}' , '{' }
};
for (auto i : s) {
if (isOpening(i)) {
st.push(i);
}
else {
if (!st.empty() && isClosing(i) && brackets.find(i)->second == st.top()) {
st.pop();
}
else if (!isClosing(i) && !isOpening(i)) continue;
else return false;
}
}
return st.empty();
}
int main(int argc, char **argv) {
string test = "{}{}{}";
cout << boolalpha << isValid(test) << endl;
test = "]";
cout << boolalpha << isValid(test) << endl;
test = "{";
cout << boolalpha << isValid(test) << endl;
test = "{]fdfdfdd";
cout << boolalpha << isValid(test) << endl;
test = "{[}]";
cout << boolalpha << isValid(test) << endl;
test = "dsd{()()[]}";
cout << boolalpha << isValid(test) << endl;
}Last updated