您的位置:首页 > 产品设计 > UI/UE

Longest Common Subsequence

2016-08-23 14:06 232 查看
Given two strings, find the longest common subsequence (LCS).

Your code should return the length of LCS.
Clarification

What's the definition of Longest Common Subsequence?
https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
http://baike.baidu.com/view/2020307.htm

Example

For 
"ABCD"
 and 
"EDCA"
,
the LCS is 
"A"
 (or 
"D"
"C"
),
return 
1
.
For 
"ABCD"
 and 
"EACB"
,
the LCS is 
"AC"
, return 
2
.

求两个字符串的最长公共子序列,用动态规划来解决。

初始化二维数组 f[A.length() + 1][B.length() + 1],    f[ i ][ j ]表示的是A的前i个字符配上前j个字符的最长公共子序列长度。

为什么不是f[A.length() ] [B.length() ]呢,因为代表的前i个或者前j个字符,是包括了0的情况。

初始值:f[ i ][ 0 ] = 0, f [ 0] [ j ] = 0, 因为和空字符串的公共子序列肯定是长度为0;

如果A的第i-1个字符等于B的第j - 1个字符,说明最长公共子序列长度加1

f[ i ][ j ]等于f[ i - 1] [ j - 1] + 1 

如果A的第i-1个字符不等于B的第j - 1个字符

f[ i ][ j ]等于 max(f[ i - 1] [ j ] , f [ i ] [ j -  1] )

注意:

因为定义f [ i ] [ j ]的i 、 j并不是下标 而是subsequence的长度

所以长度为i的字符串最后一个字符 所在的下标是i-1

public class Solution {
/**
* @param A, B: Two strings.
* @return: The length of longest common subsequence of A and B.
*/
public int longestCommonSubsequence(String A, String B) {
int m = A.length();
int n = B.length();
int[][] f = new int[m + 1][n + 1];

for (int i = 0; i < m; i++) {
f[i][0] = 0;
}
for (int j = 0; j < n; j++) {
f[0][j] = 0;
}
for (int  i = 1; i < m + 1; i++) {
for (int j = 1; j < n + 1; j++) {
if (A.charAt(i - 1) == B.charAt(j - 1)) {
f[i][j] = f[i - 1][j - 1] + 1;
} else {
f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
}
}
}
return f[m]
;
}
}


由于二维数组默认的值是0, 所以不给f[ i ][ 0 ]  和 f[ 0 ][ i ]赋初始值也是可以的,简写为:

public class Solution {
/**
* @param A, B: Two strings.
* @return: The length of longest common subsequence of A and B.
*/
public int longestCommonSubsequence(String A, String B) {
int n = A.length();
int m = B.length();
int f[][] = new int[n + 1][m + 1];
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
if(A.charAt(i - 1) == B.charAt(j - 1))
f[i][j] = f[i - 1][j - 1] + 1;
}
}
return f
[m];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode