Problem Statement could be found @https://leetcode.com/problems/valid-parentheses/
Approach -
1. Take a stack and start iterating over the string.
2. Push open bracket of any type to the stack
3. Whenever a closing bracket is encountered compare it with top element of stack.
a. If both elements are same, then remove the top most element of stack.
b. If both are different then it is an error straight away
4. If at last stack is not empty, then it is error scenario which implies opening brackets are more than closing ones
5. There is one more scenario in which error can occur. It is where there is a closing symbol at starting of string or after equilibrium state. Ex: ][] or []{}]
In this scenario stack would be empty and a closing symbol would be encountered
Code :
class Solution {
stack<char> st;
char closeBrace,sqBrackeClose, curlyBraceClose ;
char openBrace, sqBrackeOpen, curlyBraceOpen;
public:
void init(){
closeBrace = ')';
openBrace = '(';
sqBrackeClose = ']';
sqBrackeOpen = '[';
curlyBraceClose = '}';
curlyBraceOpen = '{';
}
bool isValid(string s) {
init();
for (int i=0;i<s.size();i++){
char x = s.at(i);
if ((x == curlyBraceClose ) || (x == sqBrackeClose ) || (x == closeBrace)){
if (st.size() == 0){
return false;
}else{
char atTop = st.top();
if (
( (atTop == curlyBraceOpen) && (x == curlyBraceClose) )
|| ( (atTop == sqBrackeOpen) && (x == sqBrackeClose) )
|| ( (atTop == openBrace) && (x == closeBrace ) )
){
st.pop();
}else{
return false;
}
}
}else{
st.push(x);
}
}
return (st.size() == 0);
}
};
Approach -
1. Take a stack and start iterating over the string.
2. Push open bracket of any type to the stack
3. Whenever a closing bracket is encountered compare it with top element of stack.
a. If both elements are same, then remove the top most element of stack.
b. If both are different then it is an error straight away
4. If at last stack is not empty, then it is error scenario which implies opening brackets are more than closing ones
5. There is one more scenario in which error can occur. It is where there is a closing symbol at starting of string or after equilibrium state. Ex: ][] or []{}]
In this scenario stack would be empty and a closing symbol would be encountered
Code :
class Solution {
stack<char> st;
char closeBrace,sqBrackeClose, curlyBraceClose ;
char openBrace, sqBrackeOpen, curlyBraceOpen;
public:
void init(){
closeBrace = ')';
openBrace = '(';
sqBrackeClose = ']';
sqBrackeOpen = '[';
curlyBraceClose = '}';
curlyBraceOpen = '{';
}
bool isValid(string s) {
init();
for (int i=0;i<s.size();i++){
char x = s.at(i);
if ((x == curlyBraceClose ) || (x == sqBrackeClose ) || (x == closeBrace)){
if (st.size() == 0){
return false;
}else{
char atTop = st.top();
if (
( (atTop == curlyBraceOpen) && (x == curlyBraceClose) )
|| ( (atTop == sqBrackeOpen) && (x == sqBrackeClose) )
|| ( (atTop == openBrace) && (x == closeBrace ) )
){
st.pop();
}else{
return false;
}
}
}else{
st.push(x);
}
}
return (st.size() == 0);
}
};
No comments:
Post a Comment