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
...