intlongestCommonSubstring_n2_2n(String str1, String str2){ int size1 = str1.length(); int size2 = str2.length(); if (size1 == 0 || size2 == 0) return0;
int[][] table = newint[2][size2];
// the start position of substring in original string int start1 = -1; int start2 = -1; // the longest length of common substring int longest = 0;
// record how many comparisons the solution did; // it can be used to know which algorithm is better int comparisons = 0; for (int j = 0; j < size2; ++j) { ++comparisons; if (str1.charAt(0) == str2.charAt(j)) { table[0][j] = 1; if (longest == 0) { longest = 1; start1 = 0; start2 = j; } } }
for (int i = 1; i < size1; ++i) { ++comparisons; // with odd/even to swith working row System.out.println(i & 1); int cur = ((i & 1) == 1? 1: 0); //index for current working row int pre = ((i & 1) == 0? 1: 0); //index for previous working row table[cur][0] = 0; if (str1.charAt(i) == str2.charAt(0)) { table[cur][0] = 1; if (longest == 0) { longest = 1; start1 = i; start2 = 0; } }