首页 > 其他分享 >leetcode

leetcode

时间:2022-10-23 15:56:35浏览次数:77  
标签:int text2 字符串 text1 公共 序列 leetcode

1 最长公共子序列

给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0 。
一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
    例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。
两个字符串的 公共子序列 是这两个字符串所共同拥有的子序列。

输入:text1 = "abcde", text2 = "ace" 
输出:3  
解释:最长公共子序列是 "ace" ,它的长度为 3 。
输入:text1 = "abc", text2 = "def"
输出:0
解释:两个字符串没有公共子序列,返回 0 。
方法:动态规划

 

class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        int m = text1.length();
        int n = text2.length();
        int[][] dp = new int[m+1][n+1];
        for(int i = 1;i <= m;i++){
            for(int j = 1;j <= n;j++){
                if(text1.charAt(i-1) == text2.charAt(j-1)){
                    dp[i][j] = dp[i-1][j-1]+1;
                }else{
                    dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
                }
            }
        }
        return dp[m][n];
    }
}

 

标签:int,text2,字符串,text1,公共,序列,leetcode
From: https://www.cnblogs.com/lgh544/p/16818724.html

相关文章

  • leetcode 15. 3Sum 三数之和(中等)
    一、题目大意给你一个整数数组nums,判断是否存在三元组[nums[i],nums[j],nums[k]]满足i!=j、i!=k且j!=k,同时还满足nums[i]+nums[j]+nums[k]==0。......
  • leetcode-242-easy
    ValidAnagramGiventwostringssandt,returntrueiftisananagramofs,andfalseotherwise.AnAnagramisawordorphraseformedbyrearrangingthele......
  • leetcode(31)字典树系列题目
    字典树,是一种是一种可以快速插入和搜索字符串的数据结构,有了它可以尽快的进行剪枝。将字典的信息全部转化到字典树上,只有出现在字典树上的路径,才应该被纳入到搜索空间里。......
  • leetcode-203-easy
    RemoveLinkedListElementsGiventheheadofalinkedlistandanintegerval,removeallthenodesofthelinkedlistthathasNode.val==val,andreturnth......
  • 数据结构 玩转数据结构 3-4 关于Leetcode的更多说明
    0课程地址https://coding.imooc.com/lesson/207.html#mid=13421 1重点关注1.1学习方法论1      自己花费了很多力气也解决不了的问......
  • 【重要】LeetCode 901. 股票价格跨度
    题目链接股票价格跨度注意事项使用单调栈代码classStockSpanner{public:StockSpanner(){this->stk.emplace(-1,INT_MAX);this->idx=-......
  • leetcode-283-easy
    MoveZeroes思路一:用left指针标记求解数组最大下标+1,初始化的时候是0,随着往右遍历,left会一步步扩大。最后把left右边的数都置为0。这题的关键在于left永远......
  • leetcode-231-easy
    PowerOfTwo思路一:观察2的n次方的二进制,都只有一位1bit,遍历即可publicbooleanisPowerOfTwo(intn){if(n<=0)returnfalse;intcount=0;......
  • LeetCode 1730. Shortest Path to Get Food
    原题链接在这里:https://leetcode.com/problems/shortest-path-to-get-food/题目:Youarestarvingandyouwanttoeatfoodasquicklyaspossible.Youwanttofind......
  • [LeetCode] 1768. Merge Strings Alternately
    Youaregiventwostrings word1 and word2.Mergethestringsbyaddinglettersinalternatingorder,startingwith word1.Ifastringislongerthantheot......