給定兩個字符串?text1
?和?text2
,返回這兩個字符串的最長?公共子序列?的長度。如果不存在?公共子序列?,返回?0
?。
一個字符串的?子序列?是指這樣一個新的字符串:它是由原字符串在不改變字符的相對順序的情況下刪除某些字符(也可以不刪除任何字符)后組成的新字符串。
- 例如,
"ace"
?是?"abcde"
?的子序列,但?"aec"
?不是?"abcde"
?的子序列。
兩個字符串的?公共子序列?是這兩個字符串所共同擁有的子序列。
示例 1:
輸入:text1 = "abcde", text2 = "ace" 輸出:3 解釋:最長公共子序列是 "ace" ,它的長度為 3 。
示例 2:
輸入:text1 = "abc", text2 = "abc" 輸出:3 解釋:最長公共子序列是 "abc" ,它的長度為 3 。
示例 3:
輸入:text1 = "abc", text2 = "def" 輸出:0 解釋:兩個字符串沒有公共子序列,返回 0 。
/*** @param {string} text1* @param {string} text2* @return {number}*/
var longestCommonSubsequence = function (text1, text2) {let dp = []text1 = 1+text1text2 = 2 +text2for (let i = 0; i <text1.length; i++) {dp[i] = new Array()for (let j = 0; j <text2.length; j++) {dp[i][j] = 0}}for (let i = 1; i <text1.length; i++) {for (let j = 1; j <text2.length; j++) {if(text1[i]==text2[j]){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[text1.length-1][text2.length-1]
};