Last active
June 29, 2023 15:46
-
-
Save gufranco/f564637582b39dac885089cac05dc224 to your computer and use it in GitHub Desktop.
Interview
This file contains hidden or 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
/* | |
* Implement function verify(text) which verifies whether parentheses within text are | |
* correctly nested. You need to consider three kinds: (), [], <> and only these kinds. | |
*/ | |
function verify(string) { | |
string = string.replace(/[^\(\)\[\]\{\}\<\>]/g, ''); | |
let previousString = ''; | |
while (string.length !== previousString.length) { | |
previousString = string; | |
string = string.replace(/\(\)|\[\]|\{\}|\<\>/g, ''); | |
} | |
return !string.length; | |
} | |
console.log(verify('---(++++)----')); | |
console.log(verify('')); | |
console.log(verify('before ( middle [] ) after ')); | |
console.log(verify(') (')); | |
console.log(verify('<( > )')); | |
console.log(verify('( [ <> () ] <> )')); | |
console.log(verify(' ( [)')); |
This file contains hidden or 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
/* | |
* Simplify the implementation below as much as you can. Even better | |
* if you can also improve performance as part of the simplification! | |
* FYI: This code is over 35 lines and over 300 tokens, but it can | |
* be written in 5 lines and in less than 60 tokens. | |
*/ | |
function func(s, a, b) { | |
var match_empty = /^$/; | |
if (s.match(match_empty)) { | |
return -1; | |
} else { | |
var i = s.length - 1; | |
var aIndex = -1; | |
var bIndex = -1; | |
while (aIndex == -1 && bIndex == -1 && i >= 0) { | |
if (s.substring(i, i + 1) == a) aIndex = i; | |
if (s.substring(i, i + 1) == b) bIndex = i; | |
i--; | |
} | |
if (aIndex != -1) { | |
if (bIndex == -1) return aIndex; | |
else return Math.max(aIndex, bIndex); | |
} else { | |
if (bIndex != -1) return bIndex; | |
else return -1; | |
} | |
} | |
} | |
console.log(func('abcdefgh', 'a', 'c')); | |
function newFunc(s, a, b) { | |
return (s.length) | |
? Math.max(s.lastIndexOf(a), s.lastIndexOf(b)) | |
: -1; | |
}; | |
console.log(newFunc('abcdefgh', 'a', 'c')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment