public class Solution {
public bool balanced(char parenLeft, char parenRight) {
switch (parenLeft) {
case '(':
return parenRight == ')';
break;
case '[':
return parenRight == ']';
break;
case '{':
return parenRight == '}';
break;
}
return false;
}
public bool IsValid(string s) {
HashSet<char> openParens = new HashSet<char>(){'(', '{', '['};
HashSet<char> closeParens = new HashSet<char>(){')', '}', ']'};
Stack<char> parenStack = new Stack<char>();
for (int i = 0; i < s.Length; i++) {
if (openParens.Contains(s[i])) {
parenStack.Push(s[i]);
} else if (parenStack.Count > 0 && balanced(parenStack.Peek(), s[i])) {
parenStack.Pop();
} else return false;
}
return parenStack.Count == 0;
}
}