Skip to content

Commit 2544818

Browse files
committed
feat: add palindromic-substrings, lcs solutions
1 parent 17c7d2e commit 2544818

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

longest-common-subsequence/shinsj4653.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,18 @@
1313
"""
1414

1515

16+
class Solution:
17+
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
18+
n, m = len(text1), len(text2)
19+
dp = [[0 for _ in range(m + 1)] for _ in range(n + 1)]
20+
21+
for i in range(1, n + 1):
22+
for j in range(1, m + 1):
23+
if text1[i - 1] == text2[j - 1]:
24+
dp[i][j] = dp[i - 1][j - 1] + 1
25+
26+
else:
27+
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
28+
29+
return dp[n][m]
30+
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,74 @@
11
"""
22
[문제풀이]
33
# Inputs
4+
string s
45
56
# Outputs
7+
the number of palindromic substrings
68
79
# Constraints
10+
1 <= s.length <= 1000
11+
s consists of lowercase English letters.
812
913
# Ideas
14+
부분 문자열 중 팰린드롬 인거
15+
순열?
16+
10^3 => 시초 예상
17+
18+
코드를 짜보니 O(n^3) 나오긴하는데 우선 정답
1019
1120
[회고]
1221
1322
"""
1423

1524

25+
class Solution:
26+
def countSubstrings(self, s: str) -> int:
27+
ret = 0
28+
29+
for num in range(1, len(s) + 1):
30+
for i in range(len(s) - num + 1):
31+
ss = s[i:i + num]
32+
if ss == ss[::-1]:
33+
ret += 1
34+
35+
return ret
36+
37+
# 해설보고 스스로 풀이
38+
39+
class Solution:
40+
def countSubstrings(self, s: str) -> int:
41+
dp = {}
42+
43+
for start in range(len(s)):
44+
for end in range(start, -1, -1):
45+
if start == end:
46+
dp[(start, end)] = True
47+
48+
elif start + 1 == end:
49+
dp[(start, end)] = s[start] == s[end]
50+
51+
else:
52+
dp[(start, end)] = dp[(start + 1, end - 1)] and s[start] == s[end]
53+
54+
return dp.values().count(True)
55+
56+
# 기존 값 재활용하려면 end 부터 세야하는게 이해가 안감
57+
# -> 다시 풀이
58+
class Solution:
59+
def countSubstrings(self, s: str) -> int:
60+
dp = {}
61+
62+
for end in range(len(s)):
63+
for start in range(end, -1, -1):
64+
if start == end:
65+
dp[(start, end)] = True
66+
67+
elif start + 1 == end:
68+
dp[(start, end)] = s[start] == s[end]
69+
70+
else:
71+
dp[(start, end)] = dp[(start + 1, end - 1)] and s[start] == s[end]
72+
73+
return list(dp.values()).count(True)
74+

0 commit comments

Comments
 (0)