[LeetCode]521. Longest Uncommon Subsequence I
题目描述
思路
题目描述大坑
看到要求最长非公共子序列,我以为意思是求出的子序列中不能和输入的字符串有公共子序列,动归都写好了,然后发现a不了
代码
实际ac代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int findUSlength(string a, string b) {
if (a == b)
return -1;
return max(a.size(), b.size());
}
};
int main() {
Solution s;
cout << s.findUSlength("aefawfawfawfaw", "aefawfeawfwafwaef") << endl;
system("pause");
return 0;
}
动归代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int findUSlength(string a, string b) {
int m = a.size(), n = b.size(), maxSub = 0;
vector<vector<int>> dp(m, vector<int>(n));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i == 0 || j == 0)
dp[i][j] = a[i] == b[j];
else
dp[i][j] = (a[i] == b[j]) + dp[i - 1][j - 1];
maxSub = max(maxSub, dp[i][j]);
}
}
return max(m, n) - maxSub != 0 ? min(m, n) - maxSub : -1;
}
};
int main() {
Solution s;
cout << s.findUSlength("aefawfawfawfaw", "aefawfeawfwafwaef") << endl;
system("pause");
return 0;
}