0

I need to find the longest sub string within a string.

const string = "aassqwertybbvvqwertyuivv";

const a = string.split("").reduce((previousValue, currentValue, currentIndex, array) => {
    let str = ""
    if (previousValue !== currentValue) {
    str = currentValue + str;
  }
  return str;
}, "");
console.log(a)

Here the answer shoule be 8 (qwertyui).

It just returns me the last string

Profer
  • 553
  • 8
  • 40
  • 81

1 Answers1

1

Something like this?!

const s = "aassqwertybbvvqwertyuivv"

const longest = (max, c) => c.length > max.length ? c : max

const maxs = s.replace(/(.)\1+/g, ' ')
  .split(' ')
  .reduce(longest, '')
  
console.log(maxs)
Fabiano Taioli
  • 5,270
  • 1
  • 35
  • 49