Search This Blog

2023/05/11

Interview Question Node.js

 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.Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"Output: true
Example 2:
Input: s = "()[]{}"Output: true
Example 3:
Input: s = "(]"Output: false
Constraints:
1 <= s.length <= 104s consists of parentheses only '()[]{}'.


function matchBracket(strToMatch) {
var matchArray = {
"{": "}",
"[": "]",
"(": ")"
}
var stack = []
var openingmatchBracket = ["[", "{", "("]
var closingmatchBracket = ["]", "}", ")"]

for (var char of strToMatch) {
if (openingmatchBracket.includes(char)) {
stack.push(char)
} else if (closingmatchBracket.includes(char)) {
var lastOpening = stack.pop()
if (matchArray[lastOpening] != char) {
return false;
}
}
}

return stack.length == 0
}



console.log(matchBracket('(3+{1-1)}')); // false
console.log(matchBracket('{[(3+1)+2]+}')); //true
console.log(matchBracket('[1+1]+(2*2)-{3/3}')); //true
console.log(matchBracket('(({[(((1)-2)+3)-3]/3}-3)')); //false

No comments:

Post a Comment