1062. Longest Repeating Substring

Given a string S, find out the length of the longest repeating substring(s). Return 0 if no repeating substring exists.

 

Example 1:

Input: S = "abcd"
Output: 0
Explanation: There is no repeating substring.

Example 2:

Input: S = "abbaba"
Output: 2
Explanation: The longest repeating substrings are "ab" and "ba", each of which occurs twice.

Example 3:

Input: S = "aabcaabdaab"
Output: 3
Explanation: The longest repeating substring is "aab", which occurs 3 times.

Example 4:

Input: S = "aaaaa"
Output: 4
Explanation: The longest repeating substring is "aaaa", which occurs twice.

 

Constraints:

  • The string S consists of only lowercase English letters from 'a' - 'z'.
  • 1 <= S.length <= 1500

Rust Solution

struct Solution;
use std::collections::HashSet;

impl Solution {
    fn longest_repeating_substring(s: String) -> i32 {
        let n = s.len();
        let mut res = 0;
        let mut hs: HashSet<&str> = HashSet::new();
        for k in 1..n {
            for i in 0..=n - k {
                if !hs.insert(&s[i..i + k]) {
                    res = res.max(k);
                    break;
                }
            }
            if res < k {
                break;
            }
        }
        res as i32
    }
}

#[test]
fn test() {
    let s = "abcd".to_string();
    let res = 0;
    assert_eq!(Solution::longest_repeating_substring(s), res);
    let s = "abbaba".to_string();
    let res = 2;
    assert_eq!(Solution::longest_repeating_substring(s), res);
    let s = "aabcaabdaab".to_string();
    let res = 3;
    assert_eq!(Solution::longest_repeating_substring(s), res);
    let s = "aaaaa".to_string();
    let res = 4;
    assert_eq!(Solution::longest_repeating_substring(s), res);
}

Having problems with this solution? Click here to submit an issue on github.