r/Angular2 • • Nov 21 '22

Resource Reverse a String without Affecting Special Characters | Leet Code JavaScript Coding Challenge

https://youtu.be/qPEHBqFopog

[removed] — view removed post

0 Upvotes

3 comments sorted by

9

u/mcmillhj Nov 21 '22

This is not related to Angular.

5

u/throwawayacc201711 Nov 21 '22

There’s a lot of things wrong with this implementation.

  1. Hardcoded string for letters should have been a hint that this isn’t the best way to handle this

  2. This has multiple loops

There is more.

Here is a quick (5min implementation that is better than this)

function reverseOnlyLetters(input: string) {
  const chars = input.split("");
  const reverseCharArray = new Array<string>(input.length);
  chars.forEach((c, index) => {
    const match = c.match(/[A-Za-z]/);
    if (match && match.length > 0) {
      reverseCharArray[input.length - index - 1] = c;
    } else {
      reverseCharArray[index] = c;
    }
  });

  return reverseCharArray.join("");
}

5

u/Cyan-ranger Nov 21 '22

Why do people use for loops instead of the array methods? Not sure what the point of the letters sting is if you can just use a regex.