leetcode 字符串

1143. 最长公共子序列

. - 力扣(LeetCode)

cpp 复制代码
class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        int m=text1.length();
        int n=text2.length();
        vector<vector<int>>f(m+1,vector<int>(n+1,0));
        
        
        for(int i=1;i<=m;i++){
            for(int j=1;j<=n;j++){
                if(text1[i-1]==text2[j-1])
                    f[i][j] = f[i-1][j-1]+1;
                else
                    f[i][j]= max(f[i-1][j], f[i][j-1]);
            }
        }
        return f[m][n];

    }
};

583. 两个字符串的删除操作

. - 力扣(LeetCode)

方法一:先算出最长公共子序列,在分别(word1.length - f[m][n])+ (word2.length-f[m][n]);

cpp 复制代码
class Solution {
public:
    int minDistance(string word1, string word2) {
        int m=word1.length();
        int n=word2.length();
        vector<vector<int>> f(m+1,vector<int>(n+1, 0));
        for(int i=1;i<=m;i++){
            for(int j=1;j<=n;j++){
                if(word1[i-1]==word2[j-1])
                    f[i][j] = f[i-1][j-1]+1;
                else
                    f[i][j] = max(f[i-1][j], f[i][j-1]);
            }
        }
        return m+n-2*f[m][n];
    }
};

方法二:直接定义f[i][j]:word1[0;i]和word2[0:j]变成一样的最小删除次数。

cpp 复制代码
class Solution {
public:
    int minDistance(string word1, string word2) {
        int m=word1.length();
        int n=word2.length();
        vector<vector<int>> f(m+1,vector<int>(n+1,0));
        for(int i=0;i<=m;i++)
            f[i][0] = i;
        for(int j=0;j<=n;j++)
            f[0][j] = j;

        for(int i=1;i<=m;i++){
            for(int j=1;j<=n;j++){
                if(word1[i-1]==word2[j-1])
                    f[i][j] = f[i-1][j-1];
                else
                    f[i][j] = min(f[i-1][j], f[i][j-1])+1;
                
            }
        } 
        return f[m][n];
    }
};
相关推荐
Univin20 分钟前
C++(10.5)
开发语言·c++·算法
躬身入世,以生证道22 分钟前
面试技术栈 —— 简历篇
面试·职场和发展
Asmalin36 分钟前
【代码随想录day 35】 力扣 01背包问题 一维
算法·leetcode·职场和发展
剪一朵云爱着39 分钟前
力扣2779. 数组的最大美丽值
算法·leetcode·排序算法
qq_4286396143 分钟前
虚幻基础:组件间的联动方式
c++·算法·虚幻
深瞳智检1 小时前
YOLO算法原理详解系列 第002期-YOLOv2 算法原理详解
人工智能·算法·yolo·目标检测·计算机视觉·目标跟踪
tao3556671 小时前
【Python刷力扣hot100】283. Move Zeroes
开发语言·python·leetcode
怎么没有名字注册了啊2 小时前
C++后台进程
java·c++·算法
Rubisco..2 小时前
codeforces 2.0
算法
未知陨落2 小时前
LeetCode:98.颜色分类
算法·leetcode