Skip to content

Instantly share code, notes, and snippets.

@safeng
Created November 16, 2013 07:36
Show Gist options
  • Save safeng/7497160 to your computer and use it in GitHub Desktop.
Save safeng/7497160 to your computer and use it in GitHub Desktop.
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.
class Solution {
public:
bool isValid(string s) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
static unordered_map<char,char> bMap({ {'(',0}, {')',0}, {'[',1}, {']',1}, {'{',2}, {'}',2} });
stack<char> ss;
for(int i = 0; i<s.length(); ++i)
{
char c = s[i];
if(c == '(' || c == '[' || c == '{')
ss.push(c);
else
{
if(ss.empty())
return false;
else
{
char t = ss.top();
if(bMap[t]!=bMap[c])
return false;
else
ss.pop();
}
}
}
if(!ss.empty())
return false;
else
return true;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment