Given a string with a list of parentheses composed of { [ ( } ] ) we want to return true if it is balanced. The last bracket that is opened must be the first one to be closed.
Example of valid parentheses
{[()]}
{}[]()
Solution:
Since the last bracket that is opened must also be the first one to be closed, it makes sense to use stack data structure.
public class Solution {
public bool IsValid(string s) {
Stack<char> stack = new Stack<char>();
if(s[0] == ')' || s[0] == '}' || s[0] == ']') return false;
for(int i=0; i<s.Length; i++)
{
if(s[i] == '(' || s[i] == '{' || s[i] == '[')
stack.Push(s[i]);
else if(s[i] == ')' && stack.Count !=0)
{
char ch = stack.Peek();
if(ch == '(')
stack.Pop();
else return false;
}
else if(s[i] == ']' && stack.Count !=0)
{
char ch = stack.Peek();
if(ch == '[')
stack.Pop();
else return false;
}
else if(s[i] == '}' && stack.Count !=0)
{
char ch = stack.Peek();
if(ch == '{')
stack.Pop();
else return false;
}
else
return false;
}
if(stack.Count == 0)
return true;
else
return false;
}
}