Here you can find the source of longestCommonSubstr(String s1, String s2)
Parameter | Description |
---|---|
s1 | a parameter |
s2 | a parameter |
public static int longestCommonSubstr(String s1, String s2)
//package com.java2s; public class Main { /**/*from ww w . ja v a 2 s . com*/ * This implementation appears {@code O(n^2)}. This is slower than a suffix * trie implementation, which is {@code O(n+m)}. The code below is copied * from wikipedia. * * @param s1 * @param s2 * @return the length of the longest common substring */ public static int longestCommonSubstr(String s1, String s2) { if (s1.isEmpty() || s2.isEmpty()) { return 0; } int m = s1.length(); int n = s2.length(); int cost = 0; int maxLen = 0; int[] p = new int[n]; int[] d = new int[n]; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (s1.charAt(i) != s2.charAt(j)) { cost = 0; } else { if ((i == 0) || (j == 0)) { cost = 1; } else { cost = p[j - 1] + 1; } } d[j] = cost; if (cost > maxLen) { maxLen = cost; } } // for {} int[] swap = p; p = d; d = swap; } return maxLen; } }