-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlongestSubstring.java
35 lines (30 loc) · 953 Bytes
/
longestSubstring.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//User function Template for Java
class Solution {
static String longestSubstring(String s, int n) {
// code here
int[][] LCS = new int[n + 1][n + 1];
int ansLen = 0;
int I = 0;
for(int i = 1; i <= n; i++){
for(int j = i + 1; j <= n; j++){
if(s.charAt(i - 1) == s.charAt(j - 1) && LCS[i - 1][j - 1] + 1 <= (j - i)){
LCS[i][j] = LCS[i - 1][j - 1] + 1;
if(LCS[i][j] > ansLen){
ansLen = LCS[i][j];
I = i - 1;
}
}
}
}
StringBuilder ans = new StringBuilder();
if(ansLen > 0){
for(int i = I - ansLen + 1; i <= I; i++){
ans.append(s.charAt(i));
}
}
else{
ans.append("-1");
}
return ans.toString();
}
};