28 March 2024
Easy
20. Valid Parentheses
Link: https://leetcode.com/problems/valid-parentheses
Description: Given a string s
containing just the characters (
, )
, {
, }
, [
, and ]
, determine if the input string is valid.
Solution:
Create a stack to keep track of the opening parentheses. Iterate through the string and push the closing parentheses onto the stack when an opening parenthesis is encountered. When a closing parenthesis is encountered, pop the last element from the stack and check if it matches the current closing parenthesis. If the stack is empty or the parentheses don't match, return false
. Finally, check if the stack is empty after iterating through the string.
/**
* @param {string} s
* @return {boolean}
*/
function isValid(s) {
// Initialize a stack to keep track of opening brackets
let stack = []
// Loop through each character in the string
for (let char of s) {
// If the character is an opening bracket, push its corresponding closing bracket onto the stack
if (char === '(') stack.push(')')
else if (char === '[') stack.push(']')
else if (char === '{') stack.push('}')
// If the character is a closing bracket
else {
// Pop the last element from the stack (which should be the matching opening bracket)
// If the stack is empty or the popped element does not match the current character, return false
if (stack.length === 0 || stack.pop() !== char) return false
}
}
// If the stack is empty, all brackets were properly closed; otherwise, return false
return stack.length === 0
}