Parse and balance angle brackets problem in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are given a string of angle brackets, and we are required to write a function that add brackets at the beginning and end of the string to make all brackets match.

The angle brackets match if for every < there is a corresponding > and for every > there is a corresponding <.

For example − If the input string is −

const str = '><<><';

Output

Then the output should be −

const output = '<><<><>>';

Here, we added, '<' at the beginning and '>>' at the end to balance the string.

We will use a number that will keep count of the number of open '<' tags so far. And then, when we encounter a '>' tag, if there are no current open tags, we will add '<' to the beginning of the string (while keeping the open tag count at 0).

Then, at the end, add a number of '>'s matching the number of currently open tags.

Example

The code for this will be −

const str = '><<><';
const buildPair = (str = '') => {
   let count = 0;
   let extras = 0;
   for (const char of str) {
      if (char === '>') {
         if (count === 0) {
            extras++;
         } else {
            count−−;
         };
      } else {
         count++;
      };
   };
   const leadingTags = '<'.repeat(extras);
   const trailingTags = '>'.repeat(count);
   return leadingTags + str + trailingTags;
};
console.log(buildPair(str));

Output

And the output in the console will be −

><<><>>
raja
Published on 25-Nov-2020 16:44:29
Advertisements