Advertisement
uopspop

Untitled

Jul 11th, 2021
783
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.03 KB | None | 0 0
  1. class Solution {
  2.     public int longestCommonSubsequence(String text1, String text2) {
  3.         return go(text1, text2, 0, 0);
  4.     }
  5.    
  6.     Map<String, Integer> cache = new HashMap<>();
  7.     int go(String text1, String text2, int i1, int i2) {
  8.         if (i1 == text1.length()) return 0;
  9.         if (i2 == text2.length()) return 0;
  10.        
  11.         if (cache.containsKey(get_key(i1, i2))) {
  12.             return cache.get(get_key(i1, i2));
  13.         }
  14.        
  15.         Integer len_12 = 0;
  16.         if (text1.charAt(i1) == text2.charAt(i2)) {
  17.             // one more option to do here
  18.             len_12 = 1 + go(text1, text2, i1 + 1, i2 + 1);
  19.         }
  20.        
  21.         int len_1 = go(text1, text2, i1 + 1, i2);
  22.         int len_2 = go(text1, text2, i1, i2 + 1);
  23.        
  24.         int len_best = Math.max(len_12, Math.max(len_1, len_2));
  25.        
  26.         cache.put(get_key(i1, i2), len_best);
  27.        
  28.         return len_best;
  29.     }
  30.    
  31.     String get_key(int i1, int i2) {
  32.         return "("+i1+","+i2+")";
  33.     }
  34.    
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement