Introduction
In this article, we will solve leetcode's 20th problem: Valid Parentheses. This is the best example to understand how stack works. In the last article, we implemented stack in JavaScript. In this article, we are going to solve this example in both languages C# and JavaScript.
Here is the problem from leetcode,
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.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Solution
We already know which data structure is best for this problem. Now to figure out the rest of the logic we need to find the pattern in the problem, as you can see parenthesis come in a pair, "{ }", "[ ]", "( )". We can use switch statements to find a matching pair. If we get "{" we will push "}" into the stack, if we get "[" we will push "]", if we get "('' we will push")".
There are 3 possibilities to check failed test cases,
- Having no matching pair : { (
- Having wrong matching pair: { )
- Having only one of the parenthesis: )
public class Solution {
public bool IsValid(string s) {
Stack < char > paranthesisStack = new();
foreach(char item in s) {
switch (item) {
case '{':
paranthesisStack.Push('}');
break;
case '[':
paranthesisStack.Push(']');
break;
case '(':
paranthesisStack.Push(')');
break;
case '}':
case ']':
case ')':
if (paranthesisStack.Count == 0) return false;
if (paranthesisStack.Pop() != item) return false;
break;
default:
break;
}
}
return paranthesisStack.Count == 0;
}
}
Listing 1: Valid parenthis
Test case 1: "{ ( [ ] ) }" //working test case.
Iteration 1:
Current char: {
Stack.push: }
Stack: }
Stack.Length = 1
Iteration 2:
Current char: (
Stack.push: )
Stack: ) -> }
Stack.Length = 2
Iteration 3:
Current char: [
Stack.push: ]
Stack: ] -> ) -> }
Stack.Length = 3
Iteration 4:
Current char: ]
Stack.Pop: ]
Stack: ) -> }
Stack.Length = 2
Iteration 5:
Current char: )
Stack.push: )
Stack: }
Stack.Length = 1
Iteration 6:
Current char: }
Stack.push: }
Stack: empty
Stack.Length = 0
Test Case 2: "{)" //failed test case, having wrong matching pair
Iteration 1:
Current char: {
Stack.push: }
Stack: }
Stack.Length = 1
Iteration 2:
Current char: )
Stack.Pop: }
Stack.Length = 1
Check if removing item is the same
) != }
return false
Join the conversation! Your thoughts help the community grow.