DEV Community

Discussion on: Daily Challenge #151 - Reverse Parentheses

Collapse
 
jkeane889 profile image
Jonathan Keane

Javascript

Much slower and not as elegant solution - using recursion and while loops to concatenate strings. Time complexity is terrible and looking to refactor. Would love any feedback or suggested refactoring!

`function reverseInParens(text) {
// Input - string of text that contains parantheses
// Output - reversed text inside of parantheses
// Constraints - n/a
// Edge Cases - n/a
// create global reverse string

let reversedString = '';

const reverseWitStack = (input, direction) => {
  let stack = [];

  for (let i = 0; i < input.length; i++) {
    if (input[i] === '(') {
      stack.push(input[i]);
      if (direction === true) {
        direction = false;
      } else {
        direction = true;
      };

      let j = input.length - 1;
      while (j > 0) {
        if (input[j] === ')') {
          stack.push(reverseWitStack(input.slice(i + 1, j), direction))
          stack.push(input[j]);
          if (direction === true) {
            direction = false;
          } else {
            direction = true;
          };
          i = j;
          break;
        } else {
          j--;
        }
      }
    } else {
      stack.push(input[i]);
    }
  }

  let tempString = '';

  while (stack.length) {
    if (direction === true) {
      tempString += stack.shift(); 
    } else {
      let char = stack.pop();
      if (char === ')') {
        char = '(';
      } else if (char === '(') {
        char = ')';
      }
      tempString += char;
    }
  }

  return tempString;
};

return reverseWitStack(text, true);

};

`