Skip to content

Commit

Permalink
feat: Palindromic Substrings 알고리즘 개선
Browse files Browse the repository at this point in the history
- DP 풀이법 추가
  • Loading branch information
jinah92 committed Jan 3, 2025
1 parent 137592b commit e1d03cd
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions palindromic-substrings/jinah92.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,21 @@ def countSubstrings(self, s: str) -> int:


return result

# DP 풀이
# O(N^2) times, O(N^2) spaces
# start, end 지점을 순회하면서 이전 계산값을 재사용하여 회문을 파악
class Solution2:
def countSubstrings(self, s: str) -> int:
dp = {}

for end in range(len(s)):
for start in range(end, -1, -1):
if start == end:
dp[(start, end)] = True
elif start + 1 == end:
dp[(start, end)] = s[start] == s[end]
else:
dp[(start, end)] = s[start] == s[end] and dp[(start+1, end-1)]

return list(dp.values()).count(True)

0 comments on commit e1d03cd

Please sign in to comment.