Algorithm problem: the longest common sequence (dynamic programming)

Given two strings, find the length of the longest common sequence of the two strings (Note: the longest common sequence does not need to appear consecutively, but must be in the same order)

Example:
Input: "acbbcba", "abcbbca"
Output: 6
Reason: The longest common sequence is acbbca

Problem solution: Use the method of dynamic programming to record the longest common sequence of the first i characters of string a and the first j characters of string b using a two-dimensional array to record dp[i][j].

 public int Match(String s,String m){
    
    
        int[][]dp=new int[s.length()+1][m.length()+1];
        for(int i=0;i<s.length();i++)
            for(int k=0;k<m.length();k++){
    
    
                if(s.charAt(i)==m.charAt(k))
                    dp[i+1][k+1]=dp[i][k]+1;
                else
                    dp[i+1][k+1]=Math.max(dp[i][k+1],dp[i+1][k]);
            }
        return dp[s.length()][m.length()];
    }

Guess you like

Origin blog.csdn.net/CY2333333/article/details/107991572