Question

My code works for Computing the length of the LCS but I apply the same code for Reading out an LCS on the following link,

http://en.wikipedia.org/wiki/Longest_common_subsequence_problem

but some strings are missing. Could you tell me what I am missing?

Google Playground link : http://play.golang.org/p/qnIWQqzAf5

func Back(table [][]int, str1, str2 string, i, j int) string {
  if i == 0 || j == 0 {
    return ""
  } else if str1[i] == str2[j] {
    return Back(table, str1, str2, i-1, j-1) + string(str1[i])
  } else {
    if table[i][j-1] > table[i-1][j] {
      return Back(table, str1, str2, i, j-1)
    } else {
      return Back(table, str1, str2, i-1, j)
    }
  }
}

Thanks in advance.

Was it helpful?

Solution

The problem I think is in your indexing. If you are indexing your strings from 0-len-1, your table should have number of rows and cols, 1 greater than length of strings. It seems that you have accounted that when calculating the length of LCS, but not when you are returning a LCS. Your i and j correctly represent the index for strings, but not for table, which should be 1 greater than i/j. So your base condition of checking for 0 is wrong as str1[0] and str2[0] are valid characters

So your code should look like:

func Back(table [][]int, str1, str2 string, i, j int) string {
  if i == -1 || j == -1 {
    return ""
  } else if str1[i] == str2[j] {
    return Back(table, str1, str2, i-1, j-1) + string(str1[i])
  } else {
    if table[i+1][j] > table[i][j+1] {
      return Back(table, str1, str2, i, j-1)
    } else {
      return Back(table, str1, str2, i-1, j)
    }
  }
}

Here is Live Code

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top