Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding Java Code for Day 11 #130

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
51 changes: 51 additions & 0 deletions day11/Java/LCSubstring.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* @date 05/01/19
* @author spattk (Sitesh Pattanaik)
*/

import java.util.*;

class LongestCommonSubstring
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.next();
String str2 = sc.next();

int n = str1.length();
int m = str2.length();

int[][] dp = new int[n+1][m+1];

int max = 0;
int index = 0;

for(int i=0;i<=n;i++)
{
for(int j=0;j<=m;j++)
{
if(i==0 || j==0)
dp[i][j] = 0;

else if(str1.charAt(i-1)==str2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1] + 1;
if(max<dp[i][j]){
max = dp[i][j];
index = i;
}
}
}
}

char[] result = new char[max];
int temp = max;
while(index>0 && temp>0)
{
result[temp-1] = str1.charAt(index-1);
index--;
temp--;
}
String str = new String(result);
System.out.println(str);
}
}
56 changes: 56 additions & 0 deletions day11/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,62 @@ public class longestCommonSubstring {
}
```

### [Solution](./Java/LCSubstring.java)

```java
/**
* @date 05/01/19
* @author spattk (Sitesh Pattanaik)
*/

import java.util.*;

class LongestCommonSubstring
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.next();
String str2 = sc.next();

int n = str1.length();
int m = str2.length();

int[][] dp = new int[n+1][m+1];

int max = 0;
int index = 0;

for(int i=0;i<=n;i++)
{
for(int j=0;j<=m;j++)
{
if(i==0 || j==0)
dp[i][j] = 0;

else if(str1.charAt(i-1)==str2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1] + 1;
if(max<dp[i][j]){
max = dp[i][j];
index = i;
}
}
}
}

char[] result = new char[max];
int temp = max;
while(index>0 && temp>0)
{
result[temp-1] = str1.charAt(index-1);
index--;
temp--;
}
String str = new String(result);
System.out.println(str);
}
}
```

## Python Implementation

### [Solution using dynamic programming](./Python/lcs.py)
Expand Down