Skip to content

Instantly share code, notes, and snippets.

@furf
Created May 19, 2013 18:03
Show Gist options
  • Save furf/5608438 to your computer and use it in GitHub Desktop.
Save furf/5608438 to your computer and use it in GitHub Desktop.
Given a string of brackets/parantheses, check if the string is valid. ex: [[]] is valid, ][][ is not valid. How would you solve if the parantheses could be of different types like {, [, (?
function validBrackets (brackets) {
var counts = {
'(': 0,
'[': 0,
'{': 0
},
pairs = {
')': '(',
']': '[',
'}': '{'
},
i = 0,
n = brackets.length,
bracket,
stack = [];
for (; i < n; ++i) {
bracket = brackets[i];
switch (bracket) {
case '(':
case '[':
case '{':
stack.push(bracket);
counts[bracket]++;
break;
case ')':
case ']':
case '}':
if (stack[stack.length - 1] !== pairs[bracket]) {
return false;
}
stack.pop();
break;
default:
return false;
}
}
return !stack.length;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Valid Brackets</title>
</head>
<body>
<h1>Valid Brackets</h1>
<p>Given a string of brackets/parantheses, check if the string is valid.</p>
<p>ex: [[]] is valid, ][][ is not valid.</p>
<p>How would you solve if the parantheses could be of different types like {, [, (?</p>
</body>
<script src="validBrackets.js"></script>
<script>
var isTrue = validBrackets('[[]]'),
isFalse = validBrackets('][]['),
isCrazy = validBrackets('{[()()]}([{}]){}');
console.log(isTrue, isFalse, isCrazy); // true, false, true
</script>
</html>
@maurajoglekar
Copy link

//Given a string of brackets/parantheses/curly braces, check if the string is valid.
function isValidString(str) {
var strArr = str.split('');
var matches = {'}' : '{', ']' : '[', ')' : '('};
var stack = new Array();

for (var i=0; i<strArr.length; i++) {
var char= strArr[i];

if (Object.values(matches).includes(char)) {
//opener
stack.push(char);
} else if (Object.keys(matches).includes(char)) {
//closer
if (stack[stack.length-1] !== matches[char]) {
return false;
} else {
stack.pop(char);
}
}
}
return !stack.length;
}

alert('the string is valid: ' + isValidString('{[()()]}([{}]){}'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment