Uncategorized

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;
}

KhalidAhmed
Khalid Ahmed

Expert .NET Full-Stack Developer with 10+ years building scalable business applications. Proficient in C#, ASP.NET Core, Angular, SQL, and Azure Cloud. Strong background in SDLC, APIs, microservices, and DevOps. Delivers high-performance solutions aligned with business needs. Let’s innovate together!

Khalid Ahmed

Expert .NET Full-Stack Developer with 10+ years building scalable business applications. Proficient in C#, ASP.NET Core, Angular, SQL, and Azure Cloud. Strong background in SDLC, APIs, microservices, and DevOps. Delivers high-performance solutions aligned with business needs. Let’s innovate together!

Related Articles

Leave a Reply

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

Check Also
Close
Back to top button