Java tutorial
//package com.java2s; public class Main { private static int calledTimes = 0; public static String longestCommonStringImproved(String str1, String str2) { if (str1 == null || str2 == null || str1.length() == 0 || str2.length() == 0) return null; char[] cc1 = str1.toCharArray(); char[] cc2 = str2.toCharArray(); int[][] table = new int[cc1.length + 1][cc2.length + 1]; int startIndex = 0, maxLength = 0; for (int i = 0; i < cc1.length; i++) { for (int j = 0; j < cc2.length; j++) { calledTimes++; if (cc1[i] == cc2[j]) { if (i == 0 || j == 0) table[i + 1][j + 1] = 1; else { table[i + 1][j + 1] = table[i][j] + 1; } if (table[i + 1][j + 1] > maxLength) { maxLength = table[i + 1][j + 1]; startIndex = i; } } } } // abcd bcd return str1.substring(startIndex + 1 - maxLength, startIndex + 1); } }