1. // User function Template for Java
  2.  
  3. class Solution {
  4. /**
  5.   * Find the LCS of both strings
  6.   * Once LCS length is found, we can remove the length of LCS from both the strings
  7.   * and then we can sum up the remaining length of both strings
  8.   */
  9. public int minOperations(String s1, String s2) {
  10. int n = s1.length();
  11. int m = s2.length();
  12.  
  13. // step-1 create a matrix of LCS
  14. int[][] t = new int[n+1][m+1];
  15.  
  16. // step-2 initialise the matrix
  17. for(int i=0; i<n+1; i++)
  18. {
  19. for(int j=0; j<m+1; j++)
  20. {
  21. // when string is empty, no LCS found
  22. if(i == 0 || j == 0)
  23. t[i][j] = 0;
  24. }
  25. }
  26.  
  27. // step-3 LCS iterative code
  28. for(int i=1; i<n+1; i++)
  29. {
  30. for(int j=1; j<m+1; j++)
  31. {
  32. if(s1.charAt(i-1) == s2.charAt(j-1))
  33. t[i][j] = 1 + t[i-1][j-1];
  34.  
  35. else
  36. t[i][j] = Math.max(t[i-1][j], t[i][j-1]);
  37. }
  38. }
  39.  
  40. int lcsLength = t[n][m];
  41.  
  42. int deletion = n-lcsLength;
  43. int insertion = m-lcsLength;
  44.  
  45. return deletion+insertion;
  46. }
  47. }