Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- torchserve
- 프로그래머스
- GCP
- python
- GitHub Action
- Kubernetes
- 백준
- DeepLearning
- 네이버AItech
- Matplotlib
- datascience
- autoencoder
- wandb
- 알고리즘
- pytorch
- 코딩테스트
- NLP
- rnn
- NaverAItech
- docker
- PytorchLightning
- GIT
- FastAPI
- pep8
- FDS
- vscode
- github
- Kaggle
- leetcode
- 완전탐색
Archives
- Today
- Total
Sangmun
516. Longest Palindromic Subsequence 본문
https://leetcode.com/problems/longest-palindromic-subsequence/
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
# create a 2D array of size n x n to store the lengths of longest palindromic subsequence
dp = [[0]*n for _ in range(n)]
# each character is a palindrome of length 1
for i in range(n):
dp[i][i] = 1
# loop through the string s in reverse order
for i in range(n-1, -1, -1):
# loop through the string s in forward order from i+1
for j in range(i+1, n):
if s[i] == s[j]:
# if characters at i and j match, add 2 to the length of longest palindromic subsequence
dp[i][j] = dp[i+1][j-1] + 2
else:
# if characters at i and j don't match, take the maximum of two possibilities:
# 1. exclude character at i and find longest palindromic subsequence in the remaining substring s[i+1:j+1]
# 2. exclude character at j and find longest palindromic subsequence in the remaining substring s[i:j]
dp[i][j] = max(dp[i+1][j], dp[i][j-1])
# length of longest palindromic subsequence is stored in dp[0][n-1]
return dp[0][n-1]
'알고리즘 > 리트코드' 카테고리의 다른 글
459. Repeated Substring Pattern (0) | 2023.08.12 |
---|---|
283. Move Zeroes (0) | 2023.05.04 |
Palindrome (0) | 2023.04.27 |
662. Maximum Width of Binary Tree (0) | 2023.04.20 |
Leet code Validate Stack Sequences (0) | 2023.04.13 |
Comments