Valid Parentheses | Leetcode #20 | Easy
Solution:

As mentioned in the problem statement, parentheses, braces and brackets (I will just call them brackets in the text below) should be closed by the same type. i.e '(' needs to be closed by ')' . This seems to be a pair of characters that work together. Let’s use this concept to build the algorithm to solve this problem.

Create a map called charMap which stores the opening and it’s corresponding closing character. The best suitable data structure for this use case is Stack because of it’s Last-In-First-Out(LIFO) nature i.e. last inserted element will be taken out first. So, let’s create a variable stack of type Character. For each character in the input string follow the steps from #4 to #6 If the charMap contains a key with the character, that means it is one of the opening brackets and hence we push it to the stack . Else, it is one of the closing brackets. Now, (a) get the top element from the stack using pop() method (b) get the value for that element from the charMap (c) compare it with the current character in the iteration. If they don’t match, it means they are not the matching brackets and hence we return false. There is another corner case where the closing bracket is the last character in the string after all the matching brackets or closing bracket is the only character in the input string. In this case we need to add another or condition to the if block in step #5 to check is stack is empty. In the end if the stack is empty, we have all the brackets matching and hence we return true. Otherwise return false.

This is how the code looks like —
['Rishikesh Dhokare']
['Leetcode', 'Data Structures', 'Leetcode Solution', 'Programming', 'Algorithms']