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
Solution:
var inputString = "[[1+1]+(2*2)-{3/3}<}]";
console.log("Input String:", inputString);
//remove non bracket characters
var regexNonBracketPattern = /[^<>{}[\]()]/g;
var bracketOnlyString = inputString.replace(regexNonBracketPattern, "");
//find if it has any matching bracket
console.log("Bracket Only String:", bracketOnlyString);
var regexMatchingBracketsPattern = /(\(\)|\[\]|\<\>|\{\})+/;
let hasAnyMatchingBracket =
regexMatchingBracketsPattern.test(bracketOnlyString);
console.log("Has Any Matching Bracket:", hasAnyMatchingBracket);
var counter = 1;
while (regexMatchingBracketsPattern.test(bracketOnlyString)) {
bracketOnlyString = bracketOnlyString.replace(
regexMatchingBracketsPattern,"");
if (bracketOnlyString == "") {
break;
} else {
console.log("Counter Value:", counter);
console.log("Iteration No (" + counter + "):", bracketOnlyString);
}
counter++;
}
if (bracketOnlyString.length != 0) {
console.log("Provided string has some non matching brackets");
} else {
console.log("Provided string has all matching brackets");
}
Output:
Input String: [[1+1]+(2*2)-{3/3}<}]
Bracket Only String: [[](){}<}]
Has Any Matching Bracket: true
Counter Value: 1
Iteration No (1): [<}]
Provided string has some non matching brackets
No comments:
Post a Comment