Problem Statement:
Given a string s containing just the characters '(', ')', '{', '}', '['
and ']',determine if the input string is valid.
An input string is valid if:
1) Open brackets must be closed by the same type of brackets.
2) Open brackets must be closed in the correct order.
3) 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 <= 104
s consists of parentheses only '()[]{}'.
Solution:
var str = "([{{([{([])}])}}]) [({})]";
function wellFormedBrackets(str) {
var circular = 0;
var rectangular = 0;
var curly = 0;
var brackets = {
"[": "]",
"(": ")",
"{": "}",
};
var lastOpening = [];
var lastOpeningChar = "";
for (var char of str) {
if (char == "[" || char == "(" || char == "{") {
lastOpening.push(char);
if (char == "[") {
rectangular++;
}
if (char == "{") {
curly++;
}
if (char == "(") {
circular++;
}
}
if (char == "]" || char == ")" || char == "}") {
lastOpeningChar = lastOpening.pop();
console.log("one:", lastOpeningChar);
console.log("two", char);
if (lastOpeningChar == undefined) {
console.log("No Opening brace");
return false;
} else {
if (brackets[lastOpeningChar] == char) {
if (char == "]") {
rectangular--;
}
if (char == "}") {
curly--;
}
if (char == ")") {
circular--;
}
} else {
console.log("Bracket are not properly nexted");
return false;
}
}
}
}
if (circular + rectangular + curly == 0) {
return true;
} else {
return false;
}
}
var result = wellFormedBrackets(str);
console.log("Result is", result);
No comments:
Post a Comment