문제
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
andtext2
consist of only lowercase English characters.
Solution
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
// 최장 공통 부분 문자열을 찾아야 한다.
// "abcde", "ace"
// dp[i][j]를 text1의 1번째 문자부터 i번째 문자까지와 text2의 1번째 문자부터 j번째 문자까지에서의 최장 공통 부분 수열의 길이
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][j-1], dp[i-1][j]);
}
}
return dp[m][n];
}
}
회고
두 문자열의 최장 공통 부분 문자열을 찾는 문제였다. dp[i][j]
를 text1의 1번째 문자부터 i번째 문자까지와 text2의 1번째 문자부터 j번째 문자까지의 최장 공통 부분 수열의 길이로 정의하였다.
dp 배열은 모든 요소가 기본값인 0으로 초기화되기 때문에, dp[0][0]=0
코드는 실질적으로 의미는 없으나, text1과 text2가 빈 문자열("")일 경우 최장 공통 부분 수열이 빈 문자열임을 명시적으로 보여주기 위해 추가하였다.
평소 1차원 배열로 푸는 DP 문제에 익숙했지만, 이번 문제는 2차원 배열을 활용해야 했다. 앞으로는 2차원 DP 배열을 고려한 접근 방식도 염두에 두자.
'Algorithm > LeetCode' 카테고리의 다른 글
213. House Robber II (0) | 2024.11.30 |
---|---|
377. Combination Sum IV (0) | 2024.11.17 |
139. Word Break (0) | 2024.11.11 |
300. Longest Increasing Subsequence (0) | 2024.11.07 |
322. Coin Change (0) | 2024.11.04 |