An array of parentheses are given. We need to find out if the array contains both opening and closing parentheses or not.
Steps
Declare a variable called "stack" and store an empty array.
Iterate a for loop over the given array and store the array elements inside a variable called "char".
Using switch case, check the elements and in case the individual element is an opening parenthesis, push a closing parentheses in stack array which was declared earlier.
If the individual element is not an opening parentheses, take the last element from stack array and store it inside a variable named "topElement".
If "topElement" is not equal to "char", return false.
After the completed iteration, check the length of "stack" array is zero, if it is zero, return true and if it is not zero, return false.
Runtime: 86 ms.
Memory: 42.8 MB.
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
let stack = [];
for(let i = 0; i < s.length; i++) {
let char = s[i];
switch(char) {
case "(": stack.push(")");
break;
case "{": stack.push("}");
break;
case "[": stack.push("]");
break;
default:
let topElement = stack.pop();
if(char !== topElement) {
return false;
}
}
}
return stack.length === 0;
};
π Support me: https://www.buymeacoffee.com/abusalehfaysal
π YouTube Channel: https://www.youtube.com/@thebacklogprogrammer
π PlayList Link: https://youtube.com/playlist?list=PLUnklBXn8NSefCpBaLe39mds6dQx-tDDD
π Connect with me (LinkedIn): https://www.linkedin.com/in/abusalehfaysal
π Follow our LinkedIn Page: https://www.linkedin.com/company/thebacklogprogrammer/
π Like our Facebook page: https://www.facebook.com/thebacklogprogrammer/
π Join our community (Facebook group): https://www.facebook.com/groups/5500588936676942/
π Follow me at: https://www.facebook.com/AbuSalehFaysal10
π Twitter: https://twitter.com/AbuSalehFaysal
π Abu Saleh Faysalβs Blog: https://abusalehfaysal.hashnode.dev/
π Hasnode: https://hashnode.com/@AbuSalehFaysal
π Dev Community: https://dev.to/abusalehfaysal
π freeCodeCamp: https://www.freecodecamp.org/abusalehfaysal
π Medium: https://abusalehfaysal.medium.com/
π GitHub: https://github.com/AbuSalehFaysal
π GitLab: https://gitlab.com/AbuSalehFaysal
Top comments (0)