最长公共子序列

题目:

Given two sequences, fifind the length of the longest common subsequence(LCS)

 

Note: A subsequence is difffferent from a substring, for the former need NOT be consecu

tive of the original sequence. For example, for “ABCD” and “AEFC”, the longest common

subsequence is “AC”, and the length of it is 2.

代码:

方法一——(普通方法):

int longest_Common(string s, string t) {
	int len1 = s.length(), len2 = t.length();
	vector> v(len1 + 1, vector(len2 + 1, 0));
	v[0][0] = 0;

	for (int i = 1; i <= len1; i++) {
		for (int j = 1; j <= len2; j++) {
			if (s[i - 1] == t[j - 1])v[i][j] = v[i - 1][j - 1] + 1;
			else v[i][j] = max(v[i - 1][j], v[i][j - 1]);
		}
	}

	return v[len1][len2];
}

方法二——:

 

你可能感兴趣的:(leetcode和机试题)