Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. /*
  2. Given a string of open and close parentheses return the count of
  3. parentheses need to make the string a valid string of parentheses.
  4. You are not permitted to rearrange valid parentheses to make a
  5. valid string.
  6.  
  7. Examples:
  8. - '()' => 0
  9. - ')(' => 2
  10. - '()) => 1
  11. */
  12.  
  13. const makeValidParentheses = (str) => {
  14. let unmatchedOpen = 0;
  15. let unmatchedClose = 0;
  16. for (const char of str) {
  17. // Increment the open counter
  18. if (char === '(') {
  19. unmatchedOpen += 1;
  20. }
  21.  
  22. if (char === ')') {
  23. // Decrement the open counter
  24. unmatchedOpen -= 1;
  25. if (unmatchedOpen < 0) {
  26. // If the open count is negative there is an unmatched close
  27. unmatchedClose += 1;
  28. // After accounting for the unmatched close set open back to 0
  29. unmatchedOpen = 0;
  30. }
  31. }
  32. }
  33.  
  34. return unmatchedOpen + unmatchedClose;
  35. };
  36.  
  37. // Tests
  38. const parentheses = [
  39. { input: '', output: 0 },
  40. { input: '(()', output: 1 },
  41. { input: '())', output: 1 },
  42. { input: '()()', output: 0 },
  43. { input: '()(()', output: 1 },
  44. { input: '())()', output: 1 },
  45. { input: '())(()', output: 2 },
  46. { input: '((()))', output: 0 },
  47. ];
  48.  
  49. parentheses.forEach(({ input, output }) => {
  50. console.log(`Input:\t${input}`);
  51. console.log(`Expected:\t${output}`);
  52. console.log(` Actual:\t${makeValidParentheses(input)}`);
  53. console.log();
  54. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement