-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonSubstring.java
More file actions
105 lines (84 loc) · 2.46 KB
/
Copy pathLongestCommonSubstring.java
File metadata and controls
105 lines (84 loc) · 2.46 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package LinkedInQuestions.DynamicProgramming;
/**
* Created by rmukherj on 8/11/16.
*/
public class LongestCommonSubstring {
public static int getLogestCommonSubstring(String a, String b){
int m = a.length();
int n = b.length();
int max =0;
int[][]dp = new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(a.charAt(i) == b.charAt(j)){
if(i==0 || j==0){
dp[i][j]=1;
} else{
dp[i][j]=dp[i-1][j-1]+1;
}
if(max < dp[i][j]){
max = dp[i][j];
}
}
}
}
return max;
}
//longest substring with with two distinct
public int lengthOfLongestSubstringTwoDistinct(String s){
int i=0, j= -1 , maxlen=0;
for(int k=0;k<s.length();k++){
if(s.charAt(k) == s.charAt(k-1)) continue;;
if(j>=0 && s.charAt(j)!=s.charAt(k)) {
maxlen = Math.max(k-1, maxlen);
i=j+1;
}
j=k-1;
}
return Math.max(s.length()-1,maxlen);
}
public static int getLongestCommonSubsequence(String a, String b){
int m = a.length();
int n = b.length();
int[][] dp = new int[m+1][n+1];
for(int i=0; i<=m; i++){
for(int j=0; j<=n; j++){
if(i==0 || j==0){
dp[i][j]=0;
}else if(a.charAt(i-1)==b.charAt(j-1)){
dp[i][j] = 1 + dp[i-1][j-1];
}else{
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
}
return dp[m][n];
}
}
/*
public class LongestCommonSubstring {
public static int getLongestCommonSubstring(String a, String b){
int m = a.length();
int n = b.length();
int max = 0;
int[][] dp = new int[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(a.charAt(i) == b.charAt(j)){
if(i==0 || j=0)
{
dp[i][j]=0;
} else {
dp[i][j[] = dp[i-1][j-1]+1;
}
if(max<dp[i][j])
max=dp[i][j]
}
}
}
return max;
}
}
*/