Valid Parentheses
Given a string s containing just the characters “(°, “)’. “{“,”}”,”[” and “]”, determine if the input string is valid An input string is valid if
- Open brackets must be closed by the same type of brackets,
- Open brackets must be closed in the correct order.
Constraint
1 <= s.length <= 104
s consists of parentheses only °()[]{}”
Example 1
Input: ‘07
output: valid
Example 2:
Input: s=”()[]{}”
Output: valid
Example 3
Input: s = “(]”
output: invalid
Example 4:
Input: s = “([)]”
output: invalid
Example 5)
Input: s = “{[]}”
output: valid
Solution:
public bool IsValid(string s) {
Stack stack = new Stack();
foreach (char c in s) {
if (c == '(' || c == '[' || c == '{') {
stack.Push(c);
} else if (stack.Count > 0) {
char top = stack.Pop();
if ((c == ')' && top != '(') ||
(c == ']' && top != '[') ||
(c == '}' && top != '{')) {
return false;
}
} else {
return false;
}
}
return stack.Count == 0;
}