If they want to check strings, then I would just loop over the string. I would have a variable (characterCount
) that adds one for every '(' character and subtract one for every ')'. If the end result is 0, then it's correct formatting.
EDIT: I also need to check if characterCount
is ever negative, which means that there is an incorrect formatting.
If it's an interview, ask them to clarify. Programmers that ask are more valuable than programmers that assume (and spend hours of valuable time coding wrong functionality).
function checkFormatting(str) {
const END_CHARACTER_BEFORE_START_CHARACTER = CORRECT_FORMATTING = 0;
let characterCount = CORRECT_FORMATTING;
let startCharacter = '(';
let endCharacter = ')';
for(let i = 0; i < str.length; i++) {
characterCount += Number(str[i] == startCharacter); // +1 if true
characterCount -= Number(str[i] == endCharacter); // -1 if false
if (characterCount < END_CHARACTER_BEFORE_START_CHARACTER) { // EDIT
console.log(str, false);
return false;
}
}
console.log(str, characterCount == CORRECT_FORMATTING);
return characterCount == CORRECT_FORMATTING;
}
checkFormatting('(a)'); // true
checkFormatting('((a))'); // true
checkFormatting('(a(b))'); // true
checkFormatting('(b)'); // true
checkFormatting('(b'); // false
checkFormatting('))a(('); // false