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];
    }
};
相关推荐
玖釉-3 小时前
下一个排列:从字典序到原地算法的完整推导
数据结构·c++·windows·算法
IronMurphy3 小时前
【算法五十】62. 不同路径
算法
影寂ldy3 小时前
C#一维数组
算法
过期动态4 小时前
【LeetCode 热题 100】移动零
java·数据结构·算法·leetcode·职场和发展·rabbitmq
计算机安禾4 小时前
【算法分析与设计】第10篇:下界理论与NP完全性初步
大数据·人工智能·算法
水木流年追梦5 小时前
大模型入门-大模型分布式训练2
开发语言·分布式·python·算法·正则表达式·prompt
sali-tec6 小时前
C# 基于OpenCv的视觉工作流-章78-KRT测量
图像处理·人工智能·数码相机·opencv·算法·计算机视觉
菜菜的顾清寒6 小时前
力扣HOT100(32)二叉树的中序遍历
数据结构·算法·leetcode
x2c6 小时前
数据结构:线性表中链表的建立和基本操作(C)
算法