Skip to content

Instantly share code, notes, and snippets.

@gufranco
Last active June 29, 2023 15:46
Show Gist options
  • Save gufranco/f564637582b39dac885089cac05dc224 to your computer and use it in GitHub Desktop.
Save gufranco/f564637582b39dac885089cac05dc224 to your computer and use it in GitHub Desktop.
Interview
/*
* 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(' ( [)'));
/*
* 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