class Solution {
//stack
public:
bool isValid(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<char> charStack;
for (int i = 0; i < s.size(); ++i)
{
if ( !charStack.empty() )
{
if (charStack.top() == '(' && s[i] == ')'
|| charStack.top() == '[' && s[i] == ']'
|| charStack.top() == '{' && s[i] == '}')
charStack.pop();
else charStack.push(s[i]);
}
else charStack.push(s[i]);
}
return charStack.empty();
}
};
second time
class Solution {
public:
bool matchBracket(char a, char b)
{
if(a == '[' && b == ']') return true;
if(a == '(' && b == ')') return true;
if(a == '{' && b == '}') return true;
return false;
}
bool isValid(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<char> charStack;
for(int i = 0; i < s.size(); ++i)
{
if(charStack.empty() || !matchBracket(charStack.top(), s[i])) charStack.push(s[i]);
else charStack.pop();
}
return charStack.empty();
}
};