@LIUHUAN
2019-05-21T09:29:03.000000Z
字数 3791
阅读 1049
algorithm
int minDistance(string word1, string word2) {
int m = word1.size();
int n = word2.size();
vector<vector<int>> dp(m+1,vector<int>(n+1,0));
for(int i = 0 ;i <= m ; i++) {
dp[i][0] = i;
}
for(int j = 0; j<= n ;j++) {
dp[0][j] = j;
}
for(int i = 1;i <= m; i++ ) {
for(int j = 1; j <= n; j++) {
int t = (word1[i-1] == word2[j-1]);
dp[i][j] = min(dp[i-1][j],dp[i][j-1]) + 1;
dp[i][j] = min(dp[i][j] ,dp[i-1][j-1] + 1 - t );
}
}
return dp[m][n];
}
int minimumDeleteSum(string s1, string s2) {
int m = s1.size();
int n = s2.size();
vector<vector<int>> dp(m+1,vector<int>(n+1,0));
for(int i = 1;i <= m ;i++) {
dp[i][0] = dp[i-1][0] + s1[i-1];
}
for(int j = 1; j <= n ;j++) {
dp[0][j] = dp[0][j-1] + s2[j-1];
}
for(int i = 1; i <= m; i++) {
for(int j =1 ;j <= n; j++) {
if(s1[i-1] == s2[j-1])
dp[i][j] = dp[i-1][j-1];
else
dp[i][j] = min(dp[i-1][j] + s1[i-1] ,dp[i][j-1] + s2[j-1]);
}
}
return dp[m][n];
}
int minDistance(string word1, string word2) {
int m = word1.size();
int n = word2.size();
vector<vector<int>> dp(m+1,vector<int>(n+1,0));
for(int i = 1;i <= m; i++ ) {
dp[i][0] = dp[i-1][0] + 1;
}
for(int j = 1; j <= n; j++ ) {
dp[0][j] = dp[0][j-1] + 1;
}
for(int i = 1;i <= m;i++) {
for(int j = 1;j <= n; j++) {
if(word1[i-1] == word2[j-1]) {
dp[i][j] = dp[i-1][j-1];
}else {
dp[i][j] = min(dp[i-1][j] ,dp[i][j-1]) + 1;
}
}
}
return dp[m][n];
}
int maxUncrossedLines(vector<int>& A, vector<int>& B) {
int m = A.size();
int n = B.size();
vector<vector<int>> dp(m+1,vector<int>(n+1,0));
for(int i = 1; i <= m; i++) {
for(int j = 1; j <= n; j++) {
if(A[i-1] == B[j-1])
dp[i][j] = dp[i-1][j-1] + 1;
else
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
}
}
return dp[m][n];
}
bool isSubsequence(string s, string t) {
int m = s.size();
int n = t.size();
vector<vector<int>> dp(m+1,vector<int>(n+1,0));
for(int j = 0; j <= n; j++ ) { // 默认空串是任何字符串的子序列
dp[0][j] = 1;
}
for(int i = 1; i<= m; i++ ) {
for(int j = 1; j <= n; j++ ) {
if(s[i-1] == t[j-1]) { // s[i]==t[j]
dp[i][j] = dp[i-1][j-1];
} else {
dp[i][j] = dp[i][j-1];
}
}
}
return dp[m][n];
}
int longestStrChain(vector<string>& words) {
sort(words.begin(),words.end(),[](string &s1,string &s2){return s1.length() < s2.length();});
int n = words.size();
vector<int> dp(n,1);
int maxlen = 0;
for(int i =1 ;i < n; i++ ) {
for(int j = i-1; j >= 0; j-- ) {
if( isprev(words[j] , words[i]) ) {
dp[i] = max(dp[i] , dp[j] + 1);
}
}
maxlen = max(maxlen,dp[i]);
}
return maxlen;
}
// 是否是构成链字符串的判断
int isprev(string& w1,string& w2) {
if(w1.length() +1 != w2.length())
return 0;
unordered_map<string,int> umap;
int n = w2.size();
int m = w1.size();
for(int i = 0 ;i < n ;i++ ) {
string s2(w2.begin() + i + 1 ,w2.end());
string s1(w2.begin(),w2.begin() + i);
if(s1+s2 == w1)
return 1;
}
return 0;
}
isprev
函数占用空间和时间isprev
函数