Skip to content

Commit

Permalink
2024-12-02 LCS 2
Browse files Browse the repository at this point in the history
  • Loading branch information
janghw0126 committed Dec 2, 2024
1 parent 9b612bc commit f04615a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
33 changes: 33 additions & 0 deletions janghw0126/DP/LCS2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import sys
input = sys.stdin.readline

# 문자열 입력 받기
string1 = list(input().rstrip())
string2 = list(input().rstrip())

# LCS 길이 및 LCS 문자열 저장을 위한 DP 테이블 초기화
dp_table = [[""] * (len(string2) + 1) for _ in range(len(string1) + 1)]

# DP로 LCS 계산
for i in range(1, len(string1) + 1):
for j in range(1, len(string2) + 1):
# 현재 문자가 같으면 이전 LCS에 해당 문자를 추가
if string1[i - 1] == string2[j - 1]:
dp_table[i][j] = dp_table[i - 1][j - 1] + string1[i - 1]
else:
# 현재 문자가 다를 경우 더 긴 LCS를 선택
if len(dp_table[i - 1][j]) >= len(dp_table[i][j - 1]):
dp_table[i][j] = dp_table[i - 1][j]
else:
dp_table[i][j] = dp_table[i][j - 1]

# 최종 LCS 문자열
lcs_result = dp_table[-1][-1]
# 공통 부분 수열이 없는 경우
if len(lcs_result) == 0:
# 결과 출력
print(0)
else:
# 결과 출력
print(len(lcs_result))
print(lcs_result)
1 change: 1 addition & 0 deletions janghw0126/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,5 @@
| 16차시 | 2024.10.30 | 스택 | <a href= "https://www.acmicpc.net/problem/9935">문자열 폭발</a> |[#183](https://github.com/AlgoLeadMe/AlgoLeadMe-4/pull/183) |
| 17차시 | 2024.11.3 | 이진 탐색 | <a href= "https://www.acmicpc.net/problem/1654">랜선 자르기</a> |[#186](https://github.com/AlgoLeadMe/AlgoLeadMe-4/pull/186) |
| 18차시 | 2024.11.12 | 브루트포스 | <a href= "https://www.acmicpc.net/problem/6064">카잉 달력</a> |[#188](https://github.com/AlgoLeadMe/AlgoLeadMe-4/pull/188) |
| 19차시 | 2024.12.2 | DP | <a href= "https://www.acmicpc.net/problem/9252">LCS 2</a> |[#191](https://github.com/AlgoLeadMe/AlgoLeadMe-4/pull/191) |
---

0 comments on commit f04615a

Please sign in to comment.