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 |
Tags
- GitHub Action
- 완전탐색
- torchserve
- GIT
- pytorch
- Kubernetes
- rnn
- NaverAItech
- Matplotlib
- 백준
- NLP
- 프로그래머스
- Kaggle
- FDS
- github
- vscode
- FastAPI
- 네이버AItech
- wandb
- pep8
- 알고리즘
- PytorchLightning
- DeepLearning
- docker
- datascience
- GCP
- python
- 코딩테스트
- leetcode
- autoencoder
Archives
- Today
- Total
Sangmun
516. Longest Palindromic Subsequence 본문
https://leetcode.com/problems/longest-palindromic-subsequence/
Longest Palindromic Subsequence - LeetCode
Can you solve this real interview question? Longest Palindromic Subsequence - Given a string s, find the longest palindromic subsequence's length in s. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements wi
leetcode.com
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