gelita

Longest common stubstring/subsequence given 2 strings as inp

Mar 9th, 2020
405
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.69 KB | None | 0 0
  1. /*
  2.     input: 2 strings
  3.     output: int
  4.     example: "abcde" "acdegg"
  5.     result: 2 (because "cd" is longest substring)
  6. */
  7. class Solution {
  8.     public int longestCommonSubsequence(String text1, String text2) {
  9.         int[][] result = new int[text1.length()+1][text2.length()+1];
  10.         int max = 0;
  11.         for(int i = 1; i<= text1.length();i++){
  12.             for(int j = 1; j <=text2.length();j++){
  13.                 if(text1.charAt(i-1) == text2.charAt(j-1)){
  14.                     result[i][j] = result[i-1][j-1] +1;
  15.                     if(max < result[i][j]){
  16.                         max = result[i][j];
  17.                     }  
  18.                 }
  19.             }
  20.         }
  21.         return max;
  22.     }
  23. }
Advertisement
Add Comment
Please, Sign In to add comment