Tuesday, August 25, 2020

LeetCode [1062] Longest Repeating Substring

 1062. Longest Repeating Substring

Medium

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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    public int longestRepeatingSubstring(String S) {
        int n = S.length();
        int dp[][] = new int[n][n];
        int ret = 0;
        for(int i=0; i<n; ++i){
            for(int j=i+1; j<n; ++j){
                if(S.charAt(i)==S.charAt(j)){
                    if(i==0 || j==0){
                        dp[i][j] = 1;
                        
                    }else{
                        dp[i][j] = dp[i-1][j-1]+1;
                    }
                    ret = Math.max(ret, dp[i][j]);
                }
            }
        }
        return ret;
    }
}

No comments:

Post a Comment