Created
June 14, 2016 18:42
-
-
Save korniychuk/25a8d02a1d92684c0d5c476f92b398e0 to your computer and use it in GitHub Desktop.
check correct order of the brackets in expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} str testable string | |
* | |
* @return {boolean} | |
*/ | |
function verify(str) { | |
if (typeof str !== 'string') return false; | |
var pairs = { | |
'(' : ')', | |
'{' : '}', | |
'<' : '>', | |
'[' : ']', | |
}; | |
var reversPairs = { | |
')' : '(', | |
'}' : '{', | |
'>' : '<', | |
']' : '[', | |
}; | |
var stack = []; | |
for (var i = 0, ilen = str.length; i < ilen; i++) { | |
var char = str.charAt(i); | |
if (pairs[char] !== undefined) { | |
stack.push(char); | |
} else if (reversPairs[char] !== undefined) { | |
var last = stack.pop(); | |
if (last !== reversPairs[char]) return false; | |
} | |
} | |
return !stack.length; | |
} // end verify() | |
console.log('verify("")', verify("")); | |
console.log('verify("before ( middle []) after ")', verify("before ( middle []) after ")); | |
console.log('verify(") (")', verify(") (")); | |
console.log('verify("} {")', verify("} {")); | |
console.log('verify("<( >)")', verify("<( >)")); | |
console.log('verify("( [ <> () ] <> )")', verify("( [ <> () ] <> )")); | |
console.log('verify(" ( [)")', verify(" ( [)")); | |
console.log('verify("---(++++)----")', verify("---(++++)----")); | |
console.log('verify("")', verify("")); | |
console.log('verify("before ( middle []) after ")', verify("before ( middle []) after ")); | |
console.log('verify(") (")', verify(") (")); | |
console.log('verify("} {")', verify("} {")); | |
console.log('verify("<( >)")', verify("<( >)")); | |
console.log('verify("( [ <> () ] <> )")', verify("( [ <> () ] <> )")); | |
console.log('verify(" ( [)")', verify(" ( [)")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment