|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: (Leetcode) 1143 - Longest Common Subsequence 풀이 |
| 4 | +categories: [스터디-알고리즘] |
| 5 | +tags: |
| 6 | + [자바, java, 리트코드, Leetcode, 알고리즘, matrix, dynamic programming, dp] |
| 7 | +date: 2024-07-17 02:30:00 +0900 |
| 8 | +toc: true |
| 9 | +--- |
| 10 | + |
| 11 | +기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다. |
| 12 | + |
| 13 | +[https://neetcode.io/practice](https://neetcode.io/practice) |
| 14 | + |
| 15 | +--- |
| 16 | + |
| 17 | +[https://leetcode.com/problems/longest-common-subsequence](https://leetcode.com/problems/longest-common-subsequence) |
| 18 | + |
| 19 | +## dfs를 통한 풀이 |
| 20 | + |
| 21 | +답은 대략 다 맞는것 같은데 Time Limit Exceeded 가 발생된다. |
| 22 | + |
| 23 | +```java |
| 24 | +class Solution { |
| 25 | + int longest = 0; |
| 26 | + |
| 27 | + public int longestCommonSubsequence(String text1, String text2) { |
| 28 | + dfs(text1, text2, 0, 0, 0); |
| 29 | + return longest; |
| 30 | + } |
| 31 | + |
| 32 | + private void dfs(String text1, String text2, int pointer1, int pointer2, int currentMax) { |
| 33 | + if (pointer1 == text1.length()) { |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + dfs(text1, text2, pointer1 + 1, pointer2, currentMax); // 그냥 다음 문자로 넘김, 선택하지 않는게 베스트 일 수 있음. |
| 38 | + |
| 39 | + int tempNext = text2.indexOf(text1.charAt(pointer1), pointer2); |
| 40 | + |
| 41 | + if (tempNext != -1) { |
| 42 | + if (tempNext < pointer2) { |
| 43 | + currentMax = 1; |
| 44 | + } else { |
| 45 | + currentMax++; |
| 46 | + while(pointer1 < text1.length() - 2 && tempNext < text2.length() - 2 |
| 47 | + && text1.charAt(pointer1 + 1) == text2.charAt(tempNext + 1)) { |
| 48 | + pointer1++; |
| 49 | + tempNext++; |
| 50 | + currentMax++; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + longest = Math.max(longest, currentMax); |
| 55 | + dfs(text1, text2, pointer1 + 1, tempNext + 1, currentMax); |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | +``` |
| 60 | + |
| 61 | +## dp를 통한 풀이 |
| 62 | + |
| 63 | +아마도 처음으로 접한 2차원 배열을 사용한 DP 문제가 아닐까 싶다. |
| 64 | + |
| 65 | +dp 로 접근해보니 바로 전에 푼 62번 문제와도 유사해진 것 같다. |
| 66 | + |
| 67 | +```java |
| 68 | +class Solution { |
| 69 | + public int longestCommonSubsequence(String text1, String text2) { |
| 70 | + int[][] dp = new int[text1.length() + 1][text2.length() + 1]; |
| 71 | + |
| 72 | + for (int i = 1; i < dp.length; i++) { |
| 73 | + for (int j = 1; j < dp[0].length; j++) { |
| 74 | + if (text1.charAt(i - 1) == text2.charAt(j - 1)) { |
| 75 | + dp[i][j] = dp[i - 1][j - 1] + 1; |
| 76 | + } else { |
| 77 | + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + return dp[text1.length()][text2.length()]; |
| 83 | + } |
| 84 | +} |
| 85 | +``` |
| 86 | + |
| 87 | +### TC, SC |
| 88 | + |
| 89 | +시간 복잡도는 `O(m * n)` 공간 복잡도는 `O(m * n)` 이다. |
0 commit comments