Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to find the longest repeating substring in a string with Node.js

1 Answer

0 votes
function longestCommonPrefix(sub1, sub2) {
    const min = Math.min(sub1.length, sub2.length);
    
    for (let i = 0; i < min; i++) {
        if (sub1[i] != sub2[i]) {
            return sub1.substring(0, i);
        }
    }
    return sub1.substring(0, min);
}

function longestRepeatingSubstring(s) {
    let lrs = "";
    let size = s.length;
    
    for (let i = 0; i < size; i++) {
        for (let j = i + 1; j < size; j++) {
            const lcp = longestCommonPrefix(s.substring(i, size), s.substring(j, size));
            if (lcp.length > lrs.length) {
                lrs = lcp;
            }
        }
    }
    return lrs;
}

const s = "nodejspythonphpjavacdartcppjavacsharp";

console.log(longestRepeatingSubstring(s));





/*
run

pjavac

*/

 



answered Jan 17, 2023 by avibootz

Related questions

...