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 - fmn)+ (word2.length-fmn);

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];
    }
};

方法二:直接定义fij:word10;i和word20: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];
    }
};
相关推荐
小此方16 分钟前
[算法实战论:动态规划]回文串问题的dp解法,回文串问题的母题,以及以此为基础的派生题
算法·动态规划
Pniubi1 小时前
力扣560.和为k的子数组
算法·leetcode·职场和发展
D e re k ZH1 小时前
C++ 从零入门(一):基础语法与程序结构
数据结构·c++·算法
Pniubi2 小时前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
東隅已逝,桑榆非晚4 小时前
算法6. 双指针法-查找总价格为目标的两个商品
c++·学习·算法
Eyfcom5 小时前
〖物联网终端实战 01〗UWB 室内高精度定位:仓储 AGV 与人员的厘米级轨迹追踪
物联网·算法·物流系统·快递系统·跨境物流快递系统·物联网终端实战
bro_Java6665 小时前
《排序的底层逻辑:比较、交换与分治》
java·算法·排序算法
爱喝雪碧的可乐6 小时前
MATLAB
开发语言·算法·matlab
叼烟扛炮6 小时前
Linux 学习笔记(六十):单线程的逆袭——epoll 高并发服务器实战
linux·服务器·网络·笔记·学习·算法
careathers7 小时前
【数据结构】基于比较的排序算法 - 交换排序
数据结构·算法·排序算法