Valid Parentheses Turing.com

Valid Parentheses

Given a string s containing just the characters “(°, “)’. “{“,”}”,”[” and “]”, determine if the input string is valid An input string is valid if

  1. Open brackets must be closed by the same type of brackets,
  2. 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;
}

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *