You are viewing a single comment's thread. Return to all comments →
Java8
public static int commonChild(String s1, String s2) { //watch lecture at //https://www.youtube.com/watch?v=jHGgXV27qtk //to understand how to solve //this problem using dynamic programming char c1; char c2; int max; int n = s1.length(); int[][] memo = new int[n + 1][n + 1]; for (int i = 0; i < n + 1; i++) { for (int j = 0; j < n + 1; j ++) { if (i == 0 || j == 0) { memo[i][j] = 0; } else { c1 = s1.charAt(i - 1); c2 = s2.charAt(j - 1); if (c1 != c2) { max = Math.max(memo[i - 1][j], memo[i][j - 1]); memo[i][j] = max; } else { memo[i][j] = memo[i - 1][j - 1] + 1; } } } } return memo[n][n]; /* GETTING THE LONGEST COMMON STRING int i = n; int j = n; LinkedList<Character> commonString = new LinkedList<>(); while (memo[i][i] != 0) { char c1 = s1.charAt(i - 1); char c2 = s2.charAt(j - 1); if (c1 == c2) { commonString.addFirst(c1); i--; j--; } else if (memo[i][j - 1] >= memo[i - 1][j]) { j--; } else { i--; } } StringBuilder builder = new StringBuilder(); for (Character c : commonString) { builder.appends(c); } String common = builder.toString(); */
Seems like cookies are disabled on this browser, please enable them to open this website
Common Child
You are viewing a single comment's thread. Return to all comments →
Java8