Question :
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.
Anwser 1 : Stack
class Solution {
public:
bool isValid(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<char> st;
for(int i = 0; i < s.size(); i++)
{
if(s[i] == '(' || s[i] == '{' || s[i] == '['){
st.push(s[i]);
}
if(s[i] == ')')
{
if(st.empty() || st.top() != '(')
return false;
st.pop();
}
if(s[i] == '}')
{
if(st.empty() || st.top() != '{')
return false;
st.pop();
}
if(s[i] == ']')
{
if(st.empty() || st.top() != '[')
return false;
st.pop();
}
}
if(st.empty() == 0)
return false;
return true;
}
};
Anwser 2 :
class Solution {
public:
bool isValid(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<char> st;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (isLeft(c)) { // push
st.push(c);
} else {
if (st.empty()) {
return false;
}
char d = st.top(); // pop
st.pop();
if (!match(d, c)) {
return false;
}
}
}
if (st.empty()) {
return true;
}
else {
return false;
}
}
bool isLeft(char c) {
return c == '{' || c == '[' || c == '(';
}
bool match(char c, char d) {
return (c == '(' && d == ')') || (c == '[' && d == ']') || (c == '{' && d == '}');
}
};