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];
    }
};
相关推荐
springfe01012 分钟前
构建大顶堆
前端·算法
天真小巫29 分钟前
2025.6.8
职场和发展
凌辰揽月40 分钟前
Web后端基础(基础知识)
java·开发语言·前端·数据库·学习·算法
lifallen1 小时前
深入浅出 Arrays.sort(DualPivotQuicksort):如何结合快排、归并、堆排序和插入排序
java·开发语言·数据结构·算法·排序算法
jingfeng5141 小时前
数据结构排序
数据结构·算法·排序算法
能工智人小辰1 小时前
Codeforces Round 509 (Div. 2) C. Coffee Break
c语言·c++·算法
kingmax542120081 小时前
CCF GESP202503 Grade4-B4263 [GESP202503 四级] 荒地开垦
数据结构·算法
岁忧1 小时前
LeetCode 高频 SQL 50 题(基础版)之 【高级字符串函数 / 正则表达式 / 子句】· 上
sql·算法·leetcode
eachin_z2 小时前
力扣刷题(第四十九天)
算法·leetcode·职场和发展
闻缺陷则喜何志丹2 小时前
【强连通分量 缩点 拓扑排序】P3387 【模板】缩点|普及+
c++·算法·拓扑排序·洛谷·强连通分量·缩点