Created
March 29, 2019 12:15
-
-
Save vvscode/ee0fba9763b81951e6de19f6a481c63e to your computer and use it in GitHub Desktop.
Interviews
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
/* | |
'(', '{', '[' are called "openers". | |
')', '}', ']' are called "closers". | |
Write an efficient function that tells us whether input string's openers | |
and closers are properly nested. | |
Examples: | |
"{ [ ] ( ) }" -> true | |
"{ [ ( ] ) }" -> false | |
"{ [ }" -> false | |
"class Example { public do() { return; } }" -> true | |
"class Example { public do( { return; } }" -> false | |
"<>" | |
"''" | |
"||" | |
*/ | |
const SIMILAR_BRACKETS = { | |
"'": "'", | |
"|": "|", | |
} | |
const BRACKETS = { | |
'{': '}', | |
'[': ']', | |
'(': ')', | |
'<': '>' | |
} | |
const MIRRORED_BRACKETS = Object.keys(BRACKETS).reduce((acc, el) => { | |
acc[BRACKETS[el]] = el; | |
return acc; | |
}, {}); | |
function solution(value) { | |
const stack = []; | |
const similarBracketsCounter = {}; | |
for (let i = 0; i < value.length; i++) { | |
const char = value[i]; | |
if (!BRACKETS[char] && !MIRRORED_BRACKETS[char] && !SIMILAR_BRACKETS[char]) { | |
continue; | |
} | |
if (BRACKETS[char]) { | |
// opener | |
stack.push(char); | |
} else if (MIRRORED_BRACKETS[char]) { | |
// closer | |
const lastOpener = stack[stack.length - 1]; | |
if (lastOpener !== MIRRORED_BRACKETS[char]) { | |
return false; | |
} | |
stack.pop(); | |
} else if (SIMILAR_BRACKETS[char]) { | |
similarBracketsCounter[char] = similarBracketsCounter[char] || 0; | |
similarBracketsCounter[char]++; | |
const isCloser = ( | |
similarBracketsCounter[char] % 2 === 0 && | |
stack[stack.length - 1] === char | |
); | |
if (isCloser) { | |
stack.pop(); | |
} else { | |
stack.push(char); | |
} | |
} | |
} | |
return ( | |
stack.length === 0 && | |
Object.values(similarBracketsCounter).every((el) => el % 2 === 0) | |
); | |
} | |
function test(value, expectedResult) { | |
const realResult = solution(value); | |
console.log(realResult === expectedResult, `${value} expected to give ${expectedResult}`); | |
} | |
test('', true); | |
test('some', true); | |
test('(', false); | |
test('()', true); | |
test('()[', false); | |
test('()[]', true); | |
test(')', false); | |
test('([)]', false); | |
test('((', false); | |
test('())', false); | |
// | |
test('class Example { public do() { return; } }', true); | |
test('class Example { public do( { return; } }', false); | |
test("('['", false); | |
test("(')'", false); | |
test('("("[]")")', true); | |
test("(')'", false); | |
test("'||'''", true) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment