일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- MySQL
- routes
- axios
- React
- map
- route
- JSX
- treenode
- node.js
- server
- component
- nodeJS
- bit
- Props
- DP
- event
- Navigation
- count
- 비트연산
- Callback
- UE5
- array
- Context
- c++
- priority_queue
- BinaryTree
- queue
- css
- state
- leetcode
- Today
- Total
우사미 코딩
[Leetcode] 1143. Longest Common Subsequence 본문
1. 링크
https://leetcode.com/problems/longest-common-subsequence/
Longest Common Subsequence - LeetCode
Can you solve this real interview question? 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 genera
leetcode.com
2. 키포인트
dp를 사용하여 현재 text1[i]와 text2[j]의 common subsequence의 길이를 업데이트한다
dp는 2차원 int 배열로 선언하고, 크기는 dp[text1.size()+1][text2.size()+1]로 하고 초기값은 0으로 설정한다
예를 들어 text1 = "aaaaa", text2="aaa"이라면 2차원 dp 배열의 사이즈는 dp[6][4]가 된다.
더블 for문의 i,j의 초기값은 1로 한다.
text1[i-1] == text2[j-1]라면 dp[i][j] = dp[i-1][j-1] + 1가 되고
그렇지 않다면 dp[i][j] 는 max(dp[i-1][j], dp[i][j-1])로 업데이트 해준다
for문을 다 돌고 dp를 출력해보면
0 0 0 0
0 1 1 1
0 1 2 2
0 1 2 3
0 1 2 3
0 1 2 3
배열의 가장 끝 값인 dp[5][3]에 있는게 정답이다
3. solution
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = text1.size(), n = text2.size();
vector<vector<int>> dp(m+1, vector<int>(n+1, 0));
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
if(text1[i-1] == text2[j-1]){
dp[i][j] = dp[i-1][j-1]+1;
} else {
dp[i][j] =max(dp[i-1][j], dp[i][j-1]);
}
}
}
for(auto i : dp){
for(auto j : i){
cout << j << " ";
}cout<<endl;
}
return dp[m][n];
}
};
'Leetcode' 카테고리의 다른 글
[Leetcode] 1027. Longest Arithmetic Subsequence (0) | 2023.06.24 |
---|---|
[Leetcode] 1466. Reorder Routes to Make All Paths Lead to the City Zero (0) | 2023.06.23 |
[Leetcode] 2090. K Radius Subarray Averages (0) | 2023.06.21 |
[LeetCode] 450. Delete Node in a BST (0) | 2023.06.20 |
[Leetcode] 2542. Maximum Subsequence Score (0) | 2023.06.18 |