LeetCode #20 – Valid Parentheses

Here is the next problem I will tackle:

Here is some sample output, just to make sure you understand:

Truthfully, I have actually done a problem like this before in my Computer Science class at school, however the way I did it was very inefficient, so it will be nice to solve it again, just much better. 

Firstly, when I think of an efficient way to solve this problem, I think of using the Stack class, which is a data structure that utilizes a last in first out (LIFO) approach for processing data, by using the .push() and .pop() methods. Here is how you initialize it:

As you can see, it is pretty much the same for most other data structures, such as ArrayLists, LinkedLists, Queues etc. My idea to solve this problem was to continually add the first parentheses ( ‘(‘ ‘[‘ ‘{‘ ), and then after that, pop any similar ending parentheses ( ‘)’ ‘]’ ‘}’ ). Here is how I implemented that:

What this does, is it checks if c and cc are complementary parentheses, and if they aren’t then it returns false. Also, after finishing the whole for loop, you must check if the stack is empty or not, which will determine if there are any leftover parentheses, in which case it will return false. Here is how that looks:

When you put all of that together, you get this:

Here is the output:

Here are the logistics for my solution:

Anyways, that is all from me for now. If you have any comments or suggestions, make sure to let me know down below in the comments section. I hope you guys at least learned something today, and that you all have a great day!

By:

Posted in:


Leave a comment