You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Problem Link
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/
Problem Summary
문자열 s에서 길이가 k 이상인 팰린드롬 부분 문자열을 서로 겹치지 않게 최대 몇 개 고를 수 있는지 구하는 문제.
Solution
딱 보니 DP라서 처음에는 top-down으로 풀었다.
팰린드롬 판별도
isPalindrome(l, r)로 DP를 두면 전체가 O(n^2)이 된다.처음엔 너무 편하게 둘 다
@cache를 붙였다가 메모리 초과가 났다...isPalindrome캐시만 200만 개라 350MB 가까이 먹는다. 일반 2차원 배열로 바꾸니 통과.bottom-up은 팰린드롬 표를 중심에서 양쪽으로 넓혀가면서 채우고,
dp[i+1]을 앞에서부터 채워주면 된다. dp 인덱스 때문에 좀 헤맸는데 거의 2배 빨라졌다.시간복잡도는 O(n^2)
에디토리얼을 보니 그리디로도 풀린다. 자세한건 에디토리얼 참고.
앞에서부터 보면서 길이 k 이상 팰린드롬 중 가장 빨리 끝나는 걸 고르고, 그 다음부터 다시 찾으면 된다. 왜 되는지 간단하게 정리하면
그래서 각 위치에서 길이 k, k+1짜리만 확인하면 O(nk)로 풀린다.
Source Code
Top-Down DP (6845ms)
Bottom-Up DP (3766ms)
All reactions