Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given a string of open and close parentheses return the count of
- parentheses need to make the string a valid string of parentheses.
- You are not permitted to rearrange valid parentheses to make a
- valid string.
- Examples:
- - '()' => 0
- - ')(' => 2
- - '()) => 1
- */
- const makeValidParentheses = (str) => {
- let unmatchedOpen = 0;
- let unmatchedClose = 0;
- for (const char of str) {
- // Increment the open counter
- if (char === '(') {
- unmatchedOpen += 1;
- }
- if (char === ')') {
- // Decrement the open counter
- unmatchedOpen -= 1;
- if (unmatchedOpen < 0) {
- // If the open count is negative there is an unmatched close
- unmatchedClose += 1;
- // After accounting for the unmatched close set open back to 0
- unmatchedOpen = 0;
- }
- }
- }
- return unmatchedOpen + unmatchedClose;
- };
- // Tests
- const parentheses = [
- { input: '', output: 0 },
- { input: '(()', output: 1 },
- { input: '())', output: 1 },
- { input: '()()', output: 0 },
- { input: '()(()', output: 1 },
- { input: '())()', output: 1 },
- { input: '())(()', output: 2 },
- { input: '((()))', output: 0 },
- ];
- parentheses.forEach(({ input, output }) => {
- console.log(`Input:\t${input}`);
- console.log(`Expected:\t${output}`);
- console.log(` Actual:\t${makeValidParentheses(input)}`);
- console.log();
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement