Advertisement
uopspop

Untitled

Jul 11th, 2021
774
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. class Solution {
  2.     public int longestCommonSubsequence(String text1, String text2) {
  3.        
  4.         // bottom-up solution
  5.         int[][] dp = new int[text1.length() + 1][text2.length() + 1];
  6.        
  7.         // initilize
  8.         dp[0][0] = 0;
  9.         dp[1][0] = 0;
  10.         dp[0][1] = 0;
  11.        
  12.         for (int i1 = 1; i1 <= text1.length() ;i1++) {
  13.             for (int i2 = 1; i2 <= text2.length() ;i2++) {
  14.                
  15.                 int len_12 = 0;
  16.                 if (text1.charAt(i1 - 1) == text2.charAt(i2 - 1)) {
  17.                     // one more option to do here
  18.                     len_12 = 1 + dp[i1 -1][i2 - 1];
  19.                 }
  20.                
  21.                 int len_1 = dp[i1 - 1][i2];
  22.                 int len_2 = dp[i1][i2 - 1];
  23.                
  24.                 int len_best = Math.max(len_12, Math.max(len_1, len_2));
  25.                 dp[i1][i2] = len_best;
  26.            }
  27.         }
  28.        
  29.         return dp[text1.length()][text2.length()];
  30.        
  31.         // top-down solution:
  32.         // return go(text1, text2, 0, 0);
  33.     }
  34.    
  35.     // top-down solution:
  36.     Map<String, Integer> cache = new HashMap<>();
  37.     int go(String text1, String text2, int i1, int i2) {
  38.         if (i1 == text1.length()) return 0;
  39.         if (i2 == text2.length()) return 0;
  40.        
  41.         if (cache.containsKey(get_key(i1, i2))) {
  42.             return cache.get(get_key(i1, i2));
  43.         }
  44.        
  45.         Integer len_12 = 0;
  46.         if (text1.charAt(i1) == text2.charAt(i2)) {
  47.             // one more option to do here
  48.             len_12 = 1 + go(text1, text2, i1 + 1, i2 + 1);
  49.         }
  50.        
  51.         int len_1 = go(text1, text2, i1 + 1, i2);
  52.         int len_2 = go(text1, text2, i1, i2 + 1);
  53.        
  54.         int len_best = Math.max(len_12, Math.max(len_1, len_2));
  55.        
  56.         cache.put(get_key(i1, i2), len_best);
  57.        
  58.         return len_best;
  59.     }
  60.    
  61.     String get_key(int i1, int i2) {
  62.         return "("+i1+","+i2+")";
  63.     }
  64.    
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement