您的位置:首页 > 其它

LintCode-Longest Common Substring

2014-12-31 23:13 357 查看
Given two strings, find the longest common substring.

Return the length of it.

Note

The characters in substring should occur continiously in original string. This is different with subsequnce.

Solution:

public class Solution {
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
public int longestCommonSubstring(String A, String B) {
int lenA = A.length();
int lenB = B.length();
if (lenA==0 || lenB ==0 ) return 0;

int[][] lcs = new int[lenA+1][lenB+1];
for (int i=0;i<=lenA;i++) lcs[i][0] = 0;
for (int i=0;i<=lenB;i++) lcs[0][i] = 0;

int res = 0;
for (int i=1;i<=lenA;i++)
for (int j=1;j<=lenB;j++)
if (A.charAt(i-1)==B.charAt(j-1)){
lcs[i][j]=lcs[i-1][j-1]+1;
if (lcs[i][j]>res) res = lcs[i][j];
} else lcs[i][j]=0;

return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: