Valid Parentheses
Input: s = "()"
Output: true
Input: s = "()[]{}"
Output: true
Input: s = "(]"
Output: falseSolutions
π§ Cpp
Last updated
Input: s = "()"
Output: true
Input: s = "()[]{}"
Output: true
Input: s = "(]"
Output: falseLast updated
Input: s = "([)]"
Output: false
Input: s = "{[]}"
Output: trueclass Solution
{
std::map<char,char> p_pairs
{
{'}','{'},
{')','('},
{']','['},
{'{',' '},
{'(',' '},
{'[',' '},
};
public:
bool isValid(string s)
{
std::stack<char> parenthesis;
for(char ch : s)
{
if(p_pairs[ch] == ' ')
parenthesis.push(ch);
else if(parenthesis.size() && p_pairs[ch] == parenthesis.top())
parenthesis.pop();
else
return false;
}
return parenthesis.empty();
}
};