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

1 Answer

0 votes
fn longest_common_prefix(sub1: &str, sub2: &str) -> String {
    let min_len = sub1.len().min(sub2.len());
    
    for i in 0..min_len {
        if sub1.as_bytes()[i] != sub2.as_bytes()[i] {
            return sub1[..i].to_string();
        }
    }
    
    sub1[..min_len].to_string()
}

fn longest_repeating_substring(s: &str) -> String {
    let mut lrs = String::new();
    let size = s.len();

    for i in 0..size {
        for j in i + 1..size {
            let sub1 = &s[i..];
            let sub2 = &s[j..];
            let lcp = longest_common_prefix(sub1, sub2);
            if lcp.len() > lrs.len() {
                lrs = lcp;
            }
        }
    }

    lrs
}

fn main() {
    let s = "javascriptpythonphpjavacdartcppjavacsharprust";
    
    let result = longest_repeating_substring(s);
    println!("{}", result);
}



/*
run:

pjavac

*/

 



answered Sep 23 by avibootz
...