diff --git a/README.md b/README.md index e002a466..fd8d709d 100755 --- a/README.md +++ b/README.md @@ -126,16 +126,16 @@ | | Easy | Medium | Hard | Total | |:--------:|:--------:|:--------:|:--------:|:--------:| -|Optimizing|36|38|16|90| +|Optimizing|36|37|16|89| |Accepted|**272**|**359**|**106**|**737**| |Total|474|958|383|1815| -|Perfection Rate|86.8%|89.4%|84.9%|87.8%| +|Perfection Rate|86.8%|89.7%|84.9%|87.9%| |Completion Rate|57.4%|37.5%|27.7%|40.6%| |------------|----------------------------|----------------------------|----------------------------|----------------------------| ## 二. 目录 -以下已经收录了 647 道题的题解,还有 12 道题在尝试优化到 beats 100% +以下已经收录了 648 道题的题解,还有 12 道题在尝试优化到 beats 100% | No. | Title | Solution | Acceptance | Difficulty | Frequency | |:--------:|:--------------------------------------------------------------|:--------:|:--------:|:--------:|:--------:| @@ -535,7 +535,7 @@ |0394|Decode String|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0394.Decode-String)|52.9%|Medium|| |0395|Longest Substring with At Least K Repeating Characters|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0395.Longest-Substring-with-At-Least-K-Repeating-Characters)|43.6%|Medium|| |0396|Rotate Function||36.7%|Medium|| -|0397|Integer Replacement|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0397.Integer-Replacement)|33.6%|Medium|| +|0397|Integer Replacement|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0397.Integer-Replacement)|33.5%|Medium|| |0398|Random Pick Index||58.3%|Medium|| |0399|Evaluate Division|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0399.Evaluate-Division)|54.6%|Medium|| |0400|Nth Digit||32.4%|Medium|| @@ -938,7 +938,7 @@ |0797|All Paths From Source to Target||78.6%|Medium|| |0798|Smallest Rotation with Highest Score||45.1%|Hard|| |0799|Champagne Tower||44.1%|Medium|| -|0800|Similar RGB Color||62.4%|Easy|| +|0800|Similar RGB Color||62.5%|Easy|| |0801|Minimum Swaps To Make Sequences Increasing||39.0%|Medium|| |0802|Find Eventual Safe States|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0802.Find-Eventual-Safe-States)|50.0%|Medium|| |0803|Bricks Falling When Hit|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0803.Bricks-Falling-When-Hit)|31.7%|Hard|| @@ -1141,7 +1141,7 @@ |1000|Minimum Cost to Merge Stones||40.4%|Hard|| |1001|Grid Illumination||36.0%|Hard|| |1002|Find Common Characters|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1002.Find-Common-Characters)|68.7%|Easy|| -|1003|Check If Word Is Valid After Substitutions|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1003.Check-If-Word-Is-Valid-After-Substitutions)|56.7%|Medium|| +|1003|Check If Word Is Valid After Substitutions|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1003.Check-If-Word-Is-Valid-After-Substitutions)|56.6%|Medium|| |1004|Max Consecutive Ones III|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1004.Max-Consecutive-Ones-III)|60.9%|Medium|| |1005|Maximize Sum Of Array After K Negations|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1005.Maximize-Sum-Of-Array-After-K-Negations)|52.3%|Easy|| |1006|Clumsy Factorial|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1006.Clumsy-Factorial)|53.7%|Medium|| @@ -1263,7 +1263,7 @@ |1122|Relative Sort Array|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1122.Relative-Sort-Array)|68.1%|Easy|| |1123|Lowest Common Ancestor of Deepest Leaves|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1123.Lowest-Common-Ancestor-of-Deepest-Leaves)|68.0%|Medium|| |1124|Longest Well-Performing Interval||33.3%|Medium|| -|1125|Smallest Sufficient Team||47.0%|Hard|| +|1125|Smallest Sufficient Team||46.9%|Hard|| |1126|Active Businesses||68.5%|Medium|| |1127|User Purchase Platform||50.7%|Hard|| |1128|Number of Equivalent Domino Pairs|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1128.Number-of-Equivalent-Domino-Pairs)|46.3%|Easy|| @@ -1281,7 +1281,7 @@ |1140|Stone Game II||64.7%|Medium|| |1141|User Activity for the Past 30 Days I||54.5%|Easy|| |1142|User Activity for the Past 30 Days II||35.4%|Easy|| -|1143|Longest Common Subsequence||58.7%|Medium|| +|1143|Longest Common Subsequence|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1143.Longest-Common-Subsequence)|58.7%|Medium|| |1144|Decrease Elements To Make Array Zigzag||46.2%|Medium|| |1145|Binary Tree Coloring Game|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1145.Binary-Tree-Coloring-Game)|51.3%|Medium|| |1146|Snapshot Array||36.8%|Medium|| @@ -1290,7 +1290,7 @@ |1149|Article Views II||48.3%|Medium|| |1150|Check If a Number Is Majority Element in a Sorted Array||57.2%|Easy|| |1151|Minimum Swaps to Group All 1's Together||58.8%|Medium|| -|1152|Analyze User Website Visit Pattern||43.0%|Medium|| +|1152|Analyze User Website Visit Pattern||43.1%|Medium|| |1153|String Transforms Into Another String||35.8%|Hard|| |1154|Day of the Year|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1154.Day-of-the-Year)|49.1%|Easy|| |1155|Number of Dice Rolls With Target Sum||47.6%|Medium|| @@ -1343,7 +1343,7 @@ |1202|Smallest String With Swaps|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1202.Smallest-String-With-Swaps)|49.0%|Medium|| |1203|Sort Items by Groups Respecting Dependencies|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1203.Sort-Items-by-Groups-Respecting-Dependencies)|48.4%|Hard|| |1204|Last Person to Fit in the Elevator||72.1%|Medium|| -|1205|Monthly Transactions II||45.8%|Medium|| +|1205|Monthly Transactions II||45.7%|Medium|| |1206|Design Skiplist||58.9%|Hard|| |1207|Unique Number of Occurrences|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1207.Unique-Number-of-Occurrences)|71.8%|Easy|| |1208|Get Equal Substrings Within Budget|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1208.Get-Equal-Substrings-Within-Budget)|44.2%|Medium|| @@ -1545,7 +1545,7 @@ |1404|Number of Steps to Reduce a Number in Binary Representation to One||50.0%|Medium|| |1405|Longest Happy String||52.5%|Medium|| |1406|Stone Game III||57.7%|Hard|| -|1407|Top Travellers||84.1%|Easy|| +|1407|Top Travellers||84.0%|Easy|| |1408|String Matching in an Array||63.7%|Easy|| |1409|Queries on a Permutation With Key||81.8%|Medium|| |1410|HTML Entity Parser||54.2%|Medium|| @@ -1559,9 +1559,9 @@ |1418|Display Table of Food Orders in a Restaurant||69.1%|Medium|| |1419|Minimum Number of Frogs Croaking||47.7%|Medium|| |1420|Build Array Where You Can Find The Maximum Exactly K Comparisons||64.1%|Hard|| -|1421|NPV Queries||82.3%|Medium|| +|1421|NPV Queries||82.2%|Medium|| |1422|Maximum Score After Splitting a String||57.3%|Easy|| -|1423|Maximum Points You Can Obtain from Cards|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1423.Maximum-Points-You-Can-Obtain-from-Cards)|46.8%|Medium|| +|1423|Maximum Points You Can Obtain from Cards|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1423.Maximum-Points-You-Can-Obtain-from-Cards)|46.9%|Medium|| |1424|Diagonal Traverse II||46.2%|Medium|| |1425|Constrained Subsequence Sum||45.0%|Hard|| |1426|Counting Elements||59.1%|Easy|| @@ -1600,10 +1600,10 @@ |1459|Rectangles Area||65.4%|Medium|| |1460|Make Two Arrays Equal by Reversing Sub-arrays||72.2%|Easy|| |1461|Check If a String Contains All Binary Codes of Size K|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1461.Check-If-a-String-Contains-All-Binary-Codes-of-Size-K)|54.3%|Medium|| -|1462|Course Schedule IV||44.7%|Medium|| +|1462|Course Schedule IV||44.8%|Medium|| |1463|Cherry Pickup II|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1463.Cherry-Pickup-II)|68.8%|Hard|| |1464|Maximum Product of Two Elements in an Array|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1464.Maximum-Product-of-Two-Elements-in-an-Array)|77.1%|Easy|| -|1465|Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts||33.7%|Medium|| +|1465|Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts||33.6%|Medium|| |1466|Reorder Routes to Make All Paths Lead to the City Zero||62.0%|Medium|| |1467|Probability of a Two Boxes Having The Same Number of Distinct Balls||61.0%|Hard|| |1468|Calculate Salaries||82.2%|Medium|| @@ -1611,7 +1611,7 @@ |1470|Shuffle the Array|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1470.Shuffle-the-Array)|88.2%|Easy|| |1471|The k Strongest Values in an Array||58.5%|Medium|| |1472|Design Browser History||71.8%|Medium|| -|1473|Paint House III||48.5%|Hard|| +|1473|Paint House III||48.6%|Hard|| |1474|Delete N Nodes After M Nodes of a Linked List||73.8%|Easy|| |1475|Final Prices With a Special Discount in a Shop||75.0%|Easy|| |1476|Subrectangle Queries||88.0%|Medium|| @@ -1649,7 +1649,7 @@ |1508|Range Sum of Sorted Subarray Sums||60.5%|Medium|| |1509|Minimum Difference Between Largest and Smallest Value in Three Moves||52.6%|Medium|| |1510|Stone Game IV||58.9%|Hard|| -|1511|Customer Order Frequency||74.1%|Easy|| +|1511|Customer Order Frequency||74.0%|Easy|| |1512|Number of Good Pairs|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1512.Number-of-Good-Pairs)|87.7%|Easy|| |1513|Number of Substrings With Only 1s||42.0%|Medium|| |1514|Path with Maximum Probability||40.9%|Medium|| @@ -1702,8 +1702,8 @@ |1561|Maximum Number of Coins You Can Get||77.3%|Medium|| |1562|Find Latest Group of Size M||39.7%|Medium|| |1563|Stone Game V||40.0%|Hard|| -|1564|Put Boxes Into the Warehouse I||65.5%|Medium|| -|1565|Unique Orders and Customers Per Month||83.1%|Easy|| +|1564|Put Boxes Into the Warehouse I||65.6%|Medium|| +|1565|Unique Orders and Customers Per Month||83.2%|Easy|| |1566|Detect Pattern of Length M Repeated K or More Times||42.6%|Easy|| |1567|Maximum Length of Subarray With Positive Product||36.9%|Medium|| |1568|Minimum Number of Days to Disconnect Island||50.2%|Hard|| @@ -1831,12 +1831,12 @@ |1690|Stone Game VII|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1690.Stone-Game-VII)|49.0%|Medium|| |1691|Maximum Height by Stacking Cuboids|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1691.Maximum-Height-by-Stacking-Cuboids)|50.2%|Hard|| |1692|Count Ways to Distribute Candies||61.9%|Hard|| -|1693|Daily Leads and Partners||90.8%|Easy|| +|1693|Daily Leads and Partners||90.9%|Easy|| |1694|Reformat Phone Number|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1694.Reformat-Phone-Number)|65.4%|Easy|| |1695|Maximum Erasure Value|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1695.Maximum-Erasure-Value)|49.5%|Medium|| |1696|Jump Game VI|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1696.Jump-Game-VI)|51.9%|Medium|| |1697|Checking Existence of Edge Length Limited Paths||54.3%|Hard|| -|1698|Number of Distinct Substrings in a String||60.6%|Medium|| +|1698|Number of Distinct Substrings in a String||60.7%|Medium|| |1699|Number of Calls Between Two Persons||86.3%|Medium|| |1700|Number of Students Unable to Eat Lunch|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1700.Number-of-Students-Unable-to-Eat-Lunch)|67.8%|Easy|| |1701|Average Waiting Time||61.3%|Medium|| @@ -1869,7 +1869,7 @@ |1728|Cat and Mouse II||40.9%|Hard|| |1729|Find Followers Count||71.2%|Easy|| |1730|Shortest Path to Get Food||56.5%|Medium|| -|1731|The Number of Employees Which Report to Each Employee||49.5%|Easy|| +|1731|The Number of Employees Which Report to Each Employee||49.4%|Easy|| |1732|Find the Highest Altitude|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/1732.Find-the-Highest-Altitude)|80.0%|Easy|| |1733|Minimum Number of People to Teach||37.6%|Medium|| |1734|Decode XORed Permutation||53.9%|Medium|| @@ -1926,14 +1926,14 @@ |1785|Minimum Elements to Add to Form a Given Sum||39.2%|Medium|| |1786|Number of Restricted Paths From First to Last Node||35.8%|Medium|| |1787|Make the XOR of All Segments Equal to Zero||36.4%|Hard|| -|1788|Maximize the Beauty of the Garden||70.0%|Hard|| +|1788|Maximize the Beauty of the Garden||69.8%|Hard|| |1789|Primary Department for Each Employee||79.6%|Easy|| |1790|Check if One String Swap Can Make Strings Equal||61.3%|Easy|| |1791|Find Center of Star Graph||84.9%|Medium|| |1792|Maximum Average Pass Ratio||56.2%|Medium|| |1793|Maximum Score of a Good Subarray||46.2%|Hard|| |1794|Count Pairs of Equal Substrings With Minimum Difference||68.7%|Medium|| -|1795|Rearrange Products Table||91.4%|Easy|| +|1795|Rearrange Products Table||91.5%|Easy|| |1796|Second Largest Digit in a String||48.1%|Easy|| |1797|Design Authentication Manager||48.1%|Medium|| |1798|Maximum Number of Consecutive Values You Can Make||43.5%|Medium|| @@ -1947,13 +1947,13 @@ |1806|Minimum Number of Operations to Reinitialize a Permutation||70.4%|Medium|| |1807|Evaluate the Bracket Pairs of a String||67.5%|Medium|| |1808|Maximize Number of Nice Divisors||26.9%|Hard|| -|1809|Ad-Free Sessions||73.7%|Easy|| -|1810|Minimum Path Cost in a Hidden Grid||55.9%|Medium|| -|1811|Find Interview Candidates||69.6%|Medium|| -|1812|Determine Color of a Chessboard Square||76.7%|Easy|| -|1813|Sentence Similarity III||33.6%|Medium|| -|1814|Count Nice Pairs in an Array||31.9%|Medium|| -|1815|Maximum Number of Groups Getting Fresh Donuts||25.7%|Hard|| +|1809|Ad-Free Sessions||73.8%|Easy|| +|1810|Minimum Path Cost in a Hidden Grid||55.5%|Medium|| +|1811|Find Interview Candidates||70.6%|Medium|| +|1812|Determine Color of a Chessboard Square||76.8%|Easy|| +|1813|Sentence Similarity III||33.9%|Medium|| +|1814|Count Nice Pairs in an Array||32.2%|Medium|| +|1815|Maximum Number of Groups Getting Fresh Donuts||26.5%|Hard|| |------------|-------------------------------------------------------|-------| ----------------| ---------------|-------------| ------------------------------------------------------------------ diff --git a/leetcode/1143.Longest-Common-Subsequence/1143. Longest Common Subsequence.go b/leetcode/1143.Longest-Common-Subsequence/1143. Longest Common Subsequence.go new file mode 100644 index 00000000..f81c73c9 --- /dev/null +++ b/leetcode/1143.Longest-Common-Subsequence/1143. Longest Common Subsequence.go @@ -0,0 +1,28 @@ +package leetcode + +func longestCommonSubsequence(text1 string, text2 string) int { + if len(text1) == 0 || len(text2) == 0 { + return 0 + } + dp := make([][]int, len(text1)+1) + for i := range dp { + dp[i] = make([]int, len(text2)+1) + } + for i := 1; i < len(text1)+1; i++ { + for j := 1; j < len(text2)+1; j++ { + if text1[i-1] == text2[j-1] { + dp[i][j] = dp[i-1][j-1] + 1 + } else { + dp[i][j] = max(dp[i][j-1], dp[i-1][j]) + } + } + } + return dp[len(text1)][len(text2)] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/leetcode/1143.Longest-Common-Subsequence/1143. Longest Common Subsequence_test.go b/leetcode/1143.Longest-Common-Subsequence/1143. Longest Common Subsequence_test.go new file mode 100644 index 00000000..ced01706 --- /dev/null +++ b/leetcode/1143.Longest-Common-Subsequence/1143. Longest Common Subsequence_test.go @@ -0,0 +1,53 @@ +package leetcode + +import ( + "fmt" + "testing" +) + +type question1143 struct { + para1143 + ans1143 +} + +// para 是参数 +// one 代表第一个参数 +type para1143 struct { + text1 string + text2 string +} + +// ans 是答案 +// one 代表第一个答案 +type ans1143 struct { + one int +} + +func Test_Problem1143(t *testing.T) { + + qs := []question1143{ + + { + para1143{"abcde", "ace"}, + ans1143{3}, + }, + + { + para1143{"abc", "abc"}, + ans1143{3}, + }, + + { + para1143{"abc", "def"}, + ans1143{0}, + }, + } + + fmt.Printf("------------------------Leetcode Problem 1143------------------------\n") + + for _, q := range qs { + _, p := q.ans1143, q.para1143 + fmt.Printf("【input】:%v 【output】:%v\n", p, longestCommonSubsequence(p.text1, p.text2)) + } + fmt.Printf("\n\n\n") +} diff --git a/leetcode/1143.Longest-Common-Subsequence/README.md b/leetcode/1143.Longest-Common-Subsequence/README.md new file mode 100644 index 00000000..78367ca1 --- /dev/null +++ b/leetcode/1143.Longest-Common-Subsequence/README.md @@ -0,0 +1,86 @@ +# [1143. Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/) + +## 题目 + +Given two strings `text1` and `text2`, return *the length of their longest **common subsequence**.* If there is no **common subsequence**, return `0`. + +A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. + +- For example, `"ace"` is a subsequence of `"abcde"`. + +A **common subsequence** of two strings is a subsequence that is common to both strings. + +**Example 1:** + +``` +Input: text1 = "abcde", text2 = "ace" +Output: 3 +Explanation: The longest common subsequence is "ace" and its length is 3. +``` + +**Example 2:** + +``` +Input: text1 = "abc", text2 = "abc" +Output: 3 +Explanation: The longest common subsequence is "abc" and its length is 3. +``` + +**Example 3:** + +``` +Input: text1 = "abc", text2 = "def" +Output: 0 +Explanation: There is no such common subsequence, so the result is 0. +``` + +**Constraints:** + +- `1 <= text1.length, text2.length <= 1000` +- `text1` and `text2` consist of only lowercase English characters. + +## 题目大意 + +给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0 。一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的 公共子序列 是这两个字符串所共同拥有的子序列。 + +## 解题思路 + +- 这一题是经典的最长公共子序列的问题。解题思路是二维动态规划。假设字符串 `text1` 和 `text2` 的长度分别为 `m` 和 `n`,创建 `m+1` 行 `n+1` 列的二维数组 `dp`,定义 `dp[i][j]` 表示长度为 i 的 `text1[0:i-1]` 和长度为 j 的 `text2[0:j-1]` 的最长公共子序列的长度。先考虑边界条件。当 `i = 0` 时,`text1[]` 为空字符串,它与任何字符串的最长公共子序列的长度都是 `0`,所以 `dp[0][j] = 0`。同理当 `j = 0` 时,`text2[]` 为空字符串,它与任何字符串的最长公共子序列的长度都是 `0`,所以 `dp[i][0] = 0`。由于二维数组的大小特意增加了 `1`,即 `m+1` 和 `n+1`,并且默认值是 `0`,所以不需要再初始化赋值了。 +- 当 `text1[i−1] = text2[j−1]` 时,将这两个相同的字符称为公共字符,考虑 `text1[0:i−1]` 和 `text2[0:j−1]` 的最长公共子序列,再增加一个字符(即公共字符)即可得到 `text1[0:i]` 和 `text2[0:j]` 的最长公共子序列,所以 `dp[i][j]=dp[i−1][j−1]+1`。当 `text1[i−1] != text2[j−1]` 时,最长公共子序列一定在 `text[0:i-1], text2[0:j]` 和 `text[0:i], text2[0:j-1]` 中取得。即 `dp[i][j] = max(dp[i-1][j], dp[i][j-1])`。所以状态转移方程如下: + + $$dp[i][j] = \left\{\begin{matrix}dp[i-1][j-1]+1 &,text1[i-1]=text2[j-1]\\max(dp[i-1][j],dp[i][j-1])&,text1[i-1]\neq text2[j-1]\end{matrix}\right.$$ + +- 最终结果存储在 `dp[len(text1)][len(text2)]` 中。时间复杂度 `O(mn)`,空间复杂度 `O(mn)`,其中 `m` 和 `n` 分别是 `text1` 和 `text2` 的长度。 + +## 代码 + +```go +package leetcode + +func longestCommonSubsequence(text1 string, text2 string) int { + if len(text1) == 0 || len(text2) == 0 { + return 0 + } + dp := make([][]int, len(text1)+1) + for i := range dp { + dp[i] = make([]int, len(text2)+1) + } + for i := 1; i < len(text1)+1; i++ { + for j := 1; j < len(text2)+1; j++ { + if text1[i-1] == text2[j-1] { + dp[i][j] = dp[i-1][j-1] + 1 + } else { + dp[i][j] = max(dp[i][j-1], dp[i-1][j]) + } + } + } + return dp[len(text1)][len(text2)] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` \ No newline at end of file diff --git a/website/content/ChapterFour/1100~1199/1137.N-th-Tribonacci-Number.md b/website/content/ChapterFour/1100~1199/1137.N-th-Tribonacci-Number.md index 179f6cc6..74c1b0ed 100755 --- a/website/content/ChapterFour/1100~1199/1137.N-th-Tribonacci-Number.md +++ b/website/content/ChapterFour/1100~1199/1137.N-th-Tribonacci-Number.md @@ -74,5 +74,5 @@ func tribonacci(n int) int { ----------------------------------------------
diff --git a/website/content/ChapterFour/1100~1199/1143.Longest-Common-Subsequence.md b/website/content/ChapterFour/1100~1199/1143.Longest-Common-Subsequence.md new file mode 100644 index 00000000..01e8b2fb --- /dev/null +++ b/website/content/ChapterFour/1100~1199/1143.Longest-Common-Subsequence.md @@ -0,0 +1,95 @@ +# [1143. Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/) + +## 题目 + +Given two strings `text1` and `text2`, return *the length of their longest **common subsequence**.* If there is no **common subsequence**, return `0`. + +A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. + +- For example, `"ace"` is a subsequence of `"abcde"`. + +A **common subsequence** of two strings is a subsequence that is common to both strings. + +**Example 1:** + +``` +Input: text1 = "abcde", text2 = "ace" +Output: 3 +Explanation: The longest common subsequence is "ace" and its length is 3. +``` + +**Example 2:** + +``` +Input: text1 = "abc", text2 = "abc" +Output: 3 +Explanation: The longest common subsequence is "abc" and its length is 3. +``` + +**Example 3:** + +``` +Input: text1 = "abc", text2 = "def" +Output: 0 +Explanation: There is no such common subsequence, so the result is 0. +``` + +**Constraints:** + +- `1 <= text1.length, text2.length <= 1000` +- `text1` and `text2` consist of only lowercase English characters. + +## 题目大意 + +给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0 。一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的 公共子序列 是这两个字符串所共同拥有的子序列。 + +## 解题思路 + +- 这一题是经典的最长公共子序列的问题。解题思路是二维动态规划。假设字符串 `text1` 和 `text2` 的长度分别为 `m` 和 `n`,创建 `m+1` 行 `n+1` 列的二维数组 `dp`,定义 `dp[i][j]` 表示长度为 i 的 `text1[0:i-1]` 和长度为 j 的 `text2[0:j-1]` 的最长公共子序列的长度。先考虑边界条件。当 `i = 0` 时,`text1[]` 为空字符串,它与任何字符串的最长公共子序列的长度都是 `0`,所以 `dp[0][j] = 0`。同理当 `j = 0` 时,`text2[]` 为空字符串,它与任何字符串的最长公共子序列的长度都是 `0`,所以 `dp[i][0] = 0`。由于二维数组的大小特意增加了 `1`,即 `m+1` 和 `n+1`,并且默认值是 `0`,所以不需要再初始化赋值了。 +- 当 `text1[i−1] = text2[j−1]` 时,将这两个相同的字符称为公共字符,考虑 `text1[0:i−1]` 和 `text2[0:j−1]` 的最长公共子序列,再增加一个字符(即公共字符)即可得到 `text1[0:i]` 和 `text2[0:j]` 的最长公共子序列,所以 `dp[i][j]=dp[i−1][j−1]+1`。当 `text1[i−1] != text2[j−1]` 时,最长公共子序列一定在 `text[0:i-1], text2[0:j]` 和 `text[0:i], text2[0:j-1]` 中取得。即 `dp[i][j] = max(dp[i-1][j], dp[i][j-1])`。所以状态转移方程如下: + + {{< katex display >}} + dp[i][j] = \left\{\begin{matrix}dp[i-1][j-1]+1 &,text1[i-1]=text2[j-1]\\max(dp[i-1][j],dp[i][j-1])&,text1[i-1]\neq text2[j-1]\end{matrix}\right. + {{< /katex >}} + +- 最终结果存储在 `dp[len(text1)][len(text2)]` 中。时间复杂度 `O(mn)`,空间复杂度 `O(mn)`,其中 `m` 和 `n` 分别是 `text1` 和 `text2` 的长度。 + +## 代码 + +```go +package leetcode + +func longestCommonSubsequence(text1 string, text2 string) int { + if len(text1) == 0 || len(text2) == 0 { + return 0 + } + dp := make([][]int, len(text1)+1) + for i := range dp { + dp[i] = make([]int, len(text2)+1) + } + for i := 1; i < len(text1)+1; i++ { + for j := 1; j < len(text2)+1; j++ { + if text1[i-1] == text2[j-1] { + dp[i][j] = dp[i-1][j-1] + 1 + } else { + dp[i][j] = max(dp[i][j-1], dp[i-1][j]) + } + } + } + return dp[len(text1)][len(text2)] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + + +---------------------------------------------- + diff --git a/website/content/ChapterFour/1100~1199/1145.Binary-Tree-Coloring-Game.md b/website/content/ChapterFour/1100~1199/1145.Binary-Tree-Coloring-Game.md index 047f0d03..f04cc161 100644 --- a/website/content/ChapterFour/1100~1199/1145.Binary-Tree-Coloring-Game.md +++ b/website/content/ChapterFour/1100~1199/1145.Binary-Tree-Coloring-Game.md @@ -84,6 +84,6 @@ func dfsBtreeGameWinningMove(node *TreeNode, left, right *int, x int) int { ---------------------------------------------- diff --git a/website/content/ChapterTwo/Array.md b/website/content/ChapterTwo/Array.md index d61ff67e..b3ec0f51 100644 --- a/website/content/ChapterTwo/Array.md +++ b/website/content/ChapterTwo/Array.md @@ -149,7 +149,7 @@ weight: 1 |1380|Lucky Numbers in a Matrix|[Go]({{< relref "/ChapterFour/1300~1399/1380.Lucky-Numbers-in-a-Matrix.md" >}})|Easy||||70.4%| |1385|Find the Distance Value Between Two Arrays|[Go]({{< relref "/ChapterFour/1300~1399/1385.Find-the-Distance-Value-Between-Two-Arrays.md" >}})|Easy||||66.4%| |1389|Create Target Array in the Given Order|[Go]({{< relref "/ChapterFour/1300~1399/1389.Create-Target-Array-in-the-Given-Order.md" >}})|Easy||||84.9%| -|1423|Maximum Points You Can Obtain from Cards|[Go]({{< relref "/ChapterFour/1400~1499/1423.Maximum-Points-You-Can-Obtain-from-Cards.md" >}})|Medium||||46.8%| +|1423|Maximum Points You Can Obtain from Cards|[Go]({{< relref "/ChapterFour/1400~1499/1423.Maximum-Points-You-Can-Obtain-from-Cards.md" >}})|Medium||||46.9%| |1437|Check If All 1's Are at Least Length K Places Away|[Go]({{< relref "/ChapterFour/1400~1499/1437.Check-If-All-1s-Are-at-Least-Length-K-Places-Away.md" >}})|Easy||||62.1%| |1438|Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit|[Go]({{< relref "/ChapterFour/1400~1499/1438.Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit.md" >}})|Medium||||44.4%| |1464|Maximum Product of Two Elements in an Array|[Go]({{< relref "/ChapterFour/1400~1499/1464.Maximum-Product-of-Two-Elements-in-an-Array.md" >}})|Easy||||77.1%| diff --git a/website/content/ChapterTwo/Bit_Manipulation.md b/website/content/ChapterTwo/Bit_Manipulation.md index 77fb9878..4b8fbc36 100644 --- a/website/content/ChapterTwo/Bit_Manipulation.md +++ b/website/content/ChapterTwo/Bit_Manipulation.md @@ -61,7 +61,7 @@ X & ~X = 0 |0371|Sum of Two Integers|[Go]({{< relref "/ChapterFour/0300~0399/0371.Sum-of-Two-Integers.md" >}})|Medium| O(n)| O(1)||50.6%| |0389|Find the Difference|[Go]({{< relref "/ChapterFour/0300~0399/0389.Find-the-Difference.md" >}})|Easy| O(n)| O(1)||57.9%| |0393|UTF-8 Validation|[Go]({{< relref "/ChapterFour/0300~0399/0393.UTF-8-Validation.md" >}})|Medium| O(n)| O(1)||38.1%| -|0397|Integer Replacement|[Go]({{< relref "/ChapterFour/0300~0399/0397.Integer-Replacement.md" >}})|Medium| O(n)| O(1)||33.6%| +|0397|Integer Replacement|[Go]({{< relref "/ChapterFour/0300~0399/0397.Integer-Replacement.md" >}})|Medium| O(n)| O(1)||33.5%| |0401|Binary Watch|[Go]({{< relref "/ChapterFour/0400~0499/0401.Binary-Watch.md" >}})|Easy| O(1)| O(1)||48.5%| |0405|Convert a Number to Hexadecimal|[Go]({{< relref "/ChapterFour/0400~0499/0405.Convert-a-Number-to-Hexadecimal.md" >}})|Easy| O(n)| O(1)||44.5%| |0421|Maximum XOR of Two Numbers in an Array|[Go]({{< relref "/ChapterFour/0400~0499/0421.Maximum-XOR-of-Two-Numbers-in-an-Array.md" >}})|Medium| O(n)| O(1)|❤️|54.3%| diff --git a/website/content/ChapterTwo/Dynamic_Programming.md b/website/content/ChapterTwo/Dynamic_Programming.md index addca6ba..58a4b65d 100644 --- a/website/content/ChapterTwo/Dynamic_Programming.md +++ b/website/content/ChapterTwo/Dynamic_Programming.md @@ -60,8 +60,9 @@ weight: 7 |1049|Last Stone Weight II|[Go]({{< relref "/ChapterFour/1000~1099/1049.Last-Stone-Weight-II.md" >}})|Medium||||45.8%| |1074|Number of Submatrices That Sum to Target|[Go]({{< relref "/ChapterFour/1000~1099/1074.Number-of-Submatrices-That-Sum-to-Target.md" >}})|Hard||||62.0%| |1105|Filling Bookcase Shelves|[Go]({{< relref "/ChapterFour/1100~1199/1105.Filling-Bookcase-Shelves.md" >}})|Medium||||57.5%| +|1143|Longest Common Subsequence|[Go]({{< relref "/ChapterFour/1100~1199/1143.Longest-Common-Subsequence.md" >}})|Medium||||58.7%| |1235|Maximum Profit in Job Scheduling|[Go]({{< relref "/ChapterFour/1200~1299/1235.Maximum-Profit-in-Job-Scheduling.md" >}})|Hard||||47.6%| -|1423|Maximum Points You Can Obtain from Cards|[Go]({{< relref "/ChapterFour/1400~1499/1423.Maximum-Points-You-Can-Obtain-from-Cards.md" >}})|Medium||||46.8%| +|1423|Maximum Points You Can Obtain from Cards|[Go]({{< relref "/ChapterFour/1400~1499/1423.Maximum-Points-You-Can-Obtain-from-Cards.md" >}})|Medium||||46.9%| |1463|Cherry Pickup II|[Go]({{< relref "/ChapterFour/1400~1499/1463.Cherry-Pickup-II.md" >}})|Hard||||68.8%| |1641|Count Sorted Vowel Strings|[Go]({{< relref "/ChapterFour/1600~1699/1641.Count-Sorted-Vowel-Strings.md" >}})|Medium||||75.8%| |1654|Minimum Jumps to Reach Home|[Go]({{< relref "/ChapterFour/1600~1699/1654.Minimum-Jumps-to-Reach-Home.md" >}})|Medium||||25.2%| diff --git a/website/content/ChapterTwo/Math.md b/website/content/ChapterTwo/Math.md index 76d50ff5..e2ac2955 100644 --- a/website/content/ChapterTwo/Math.md +++ b/website/content/ChapterTwo/Math.md @@ -37,7 +37,7 @@ weight: 12 |0357|Count Numbers with Unique Digits|[Go]({{< relref "/ChapterFour/0300~0399/0357.Count-Numbers-with-Unique-Digits.md" >}})|Medium| O(1)| O(1)||48.9%| |0367|Valid Perfect Square|[Go]({{< relref "/ChapterFour/0300~0399/0367.Valid-Perfect-Square.md" >}})|Easy||||42.1%| |0372|Super Pow|[Go]({{< relref "/ChapterFour/0300~0399/0372.Super-Pow.md" >}})|Medium||||36.8%| -|0397|Integer Replacement|[Go]({{< relref "/ChapterFour/0300~0399/0397.Integer-Replacement.md" >}})|Medium||||33.6%| +|0397|Integer Replacement|[Go]({{< relref "/ChapterFour/0300~0399/0397.Integer-Replacement.md" >}})|Medium||||33.5%| |0413|Arithmetic Slices|[Go]({{< relref "/ChapterFour/0400~0499/0413.Arithmetic-Slices.md" >}})|Medium||||60.0%| |0423|Reconstruct Original Digits from English|[Go]({{< relref "/ChapterFour/0400~0499/0423.Reconstruct-Original-Digits-from-English.md" >}})|Medium||||50.9%| |0441|Arranging Coins|[Go]({{< relref "/ChapterFour/0400~0499/0441.Arranging-Coins.md" >}})|Easy||||42.6%| diff --git a/website/content/ChapterTwo/Sliding_Window.md b/website/content/ChapterTwo/Sliding_Window.md index 3fe40d28..3960f863 100644 --- a/website/content/ChapterTwo/Sliding_Window.md +++ b/website/content/ChapterTwo/Sliding_Window.md @@ -44,7 +44,7 @@ weight: 17 |1052|Grumpy Bookstore Owner|[Go]({{< relref "/ChapterFour/1000~1099/1052.Grumpy-Bookstore-Owner.md" >}})|Medium| O(n log n)| O(1) ||55.9%| |1074|Number of Submatrices That Sum to Target|[Go]({{< relref "/ChapterFour/1000~1099/1074.Number-of-Submatrices-That-Sum-to-Target.md" >}})|Hard| O(n^3)| O(n) |❤️|62.0%| |1208|Get Equal Substrings Within Budget|[Go]({{< relref "/ChapterFour/1200~1299/1208.Get-Equal-Substrings-Within-Budget.md" >}})|Medium||||44.2%| -|1423|Maximum Points You Can Obtain from Cards|[Go]({{< relref "/ChapterFour/1400~1499/1423.Maximum-Points-You-Can-Obtain-from-Cards.md" >}})|Medium||||46.8%| +|1423|Maximum Points You Can Obtain from Cards|[Go]({{< relref "/ChapterFour/1400~1499/1423.Maximum-Points-You-Can-Obtain-from-Cards.md" >}})|Medium||||46.9%| |1438|Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit|[Go]({{< relref "/ChapterFour/1400~1499/1438.Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit.md" >}})|Medium||||44.4%| |1658|Minimum Operations to Reduce X to Zero|[Go]({{< relref "/ChapterFour/1600~1699/1658.Minimum-Operations-to-Reduce-X-to-Zero.md" >}})|Medium||||33.3%| |------------|-------------------------------------------------------|-------| ----------------| ---------------|-------------|-------------|-------------| diff --git a/website/content/ChapterTwo/Stack.md b/website/content/ChapterTwo/Stack.md index bd949209..c9dc5a96 100644 --- a/website/content/ChapterTwo/Stack.md +++ b/website/content/ChapterTwo/Stack.md @@ -53,7 +53,7 @@ weight: 5 |0907|Sum of Subarray Minimums|[Go]({{< relref "/ChapterFour/0900~0999/0907.Sum-of-Subarray-Minimums.md" >}})|Medium| O(n)| O(n)|❤️|33.1%| |0921|Minimum Add to Make Parentheses Valid|[Go]({{< relref "/ChapterFour/0900~0999/0921.Minimum-Add-to-Make-Parentheses-Valid.md" >}})|Medium| O(n)| O(n)||74.9%| |0946|Validate Stack Sequences|[Go]({{< relref "/ChapterFour/0900~0999/0946.Validate-Stack-Sequences.md" >}})|Medium| O(n)| O(n)||64.4%| -|1003|Check If Word Is Valid After Substitutions|[Go]({{< relref "/ChapterFour/1000~1099/1003.Check-If-Word-Is-Valid-After-Substitutions.md" >}})|Medium| O(n)| O(1)||56.7%| +|1003|Check If Word Is Valid After Substitutions|[Go]({{< relref "/ChapterFour/1000~1099/1003.Check-If-Word-Is-Valid-After-Substitutions.md" >}})|Medium| O(n)| O(1)||56.6%| |1019|Next Greater Node In Linked List|[Go]({{< relref "/ChapterFour/1000~1099/1019.Next-Greater-Node-In-Linked-List.md" >}})|Medium| O(n)| O(1)||58.3%| |1021|Remove Outermost Parentheses|[Go]({{< relref "/ChapterFour/1000~1099/1021.Remove-Outermost-Parentheses.md" >}})|Easy| O(n)| O(1)||79.2%| |1047|Remove All Adjacent Duplicates In String|[Go]({{< relref "/ChapterFour/1000~1099/1047.Remove-All-Adjacent-Duplicates-In-String.md" >}})|Easy| O(n)| O(1)||71.1%| diff --git a/website/content/ChapterTwo/String.md b/website/content/ChapterTwo/String.md index abf580ca..c4221158 100644 --- a/website/content/ChapterTwo/String.md +++ b/website/content/ChapterTwo/String.md @@ -49,7 +49,7 @@ weight: 2 |0916|Word Subsets|[Go]({{< relref "/ChapterFour/0900~0999/0916.Word-Subsets.md" >}})|Medium||||52.8%| |0925|Long Pressed Name|[Go]({{< relref "/ChapterFour/0900~0999/0925.Long-Pressed-Name.md" >}})|Easy| O(n)| O(1)||37.5%| |0966|Vowel Spellchecker|[Go]({{< relref "/ChapterFour/0900~0999/0966.Vowel-Spellchecker.md" >}})|Medium||||51.9%| -|1003|Check If Word Is Valid After Substitutions|[Go]({{< relref "/ChapterFour/1000~1099/1003.Check-If-Word-Is-Valid-After-Substitutions.md" >}})|Medium| O(n)| O(1)||56.7%| +|1003|Check If Word Is Valid After Substitutions|[Go]({{< relref "/ChapterFour/1000~1099/1003.Check-If-Word-Is-Valid-After-Substitutions.md" >}})|Medium| O(n)| O(1)||56.6%| |1108|Defanging an IP Address|[Go]({{< relref "/ChapterFour/1100~1199/1108.Defanging-an-IP-Address.md" >}})|Easy||||88.4%| |1170|Compare Strings by Frequency of the Smallest Character|[Go]({{< relref "/ChapterFour/1100~1199/1170.Compare-Strings-by-Frequency-of-the-Smallest-Character.md" >}})|Medium||||60.3%| |1189|Maximum Number of Balloons|[Go]({{< relref "/ChapterFour/1100~1199/1189.Maximum-Number-of-Balloons.md" >}})|Easy||||62.2%|