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,845 questions

51,766 answers

573 users

How to find the longest repeating substring in a string with Swift

1 Answer

0 votes
import Foundation

// Function to find the longest common prefix between two strings
func longestCommonPrefix(_ sub1: String, _ sub2: String) -> String {
    let minLen = min(sub1.count, sub2.count)
    
    for i in 0..<minLen {
        let index1 = sub1.index(sub1.startIndex, offsetBy: i)
        let index2 = sub2.index(sub2.startIndex, offsetBy: i)
        if sub1[index1] != sub2[index2] {
            return String(sub1[..<index1])
        }
    }
    let endIndex = sub1.index(sub1.startIndex, offsetBy: minLen)
    
    return String(sub1[..<endIndex])
}

// Function to find the longest repeating substring
func longestRepeatingSubstring(_ s: String) -> String {
    var lrs = ""
    let size = s.count
    let characters = Array(s)

    for i in 0..<size {
        for j in i + 1..<size {
            let sub1 = String(characters[i..<size])
            let sub2 = String(characters[j..<size])
            let lcp = longestCommonPrefix(sub1, sub2)
            if lcp.count > lrs.count {
                lrs = lcp
            }
        }
    }

    return lrs
}

let s = "javascriptpythonphpjavacdartcppjavacsharpswift"
print(longestRepeatingSubstring(s))



/*
run:

pjavac

*/

 



answered Sep 23, 2025 by avibootz
...