Skip to content

Commit a8e5f12

Browse files
committed
Solve Palindromic substrings problem
1 parent 91e1fbe commit a8e5f12

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
"""
2+
Constraints:
3+
- 1 <= s.length <= 1000
4+
- s consists of lowercase English letters.
5+
6+
<Solution 2>
7+
8+
Time Complexity: O(nยฒ)
9+
- ์™ธ๋ถ€ for๋ฌธ: n๋ฒˆ ์‹คํ–‰
10+
- ๋‚ด๋ถ€ ํ•จ์ˆ˜ (expand_around_center): ์ตœ์•…์˜ ๊ฒฝ์šฐ n๋ฒˆ ํ™•์žฅ
11+
- ๊ฒฐ๊ณผ: n * n = O(nยฒ)
12+
13+
Space Complexity: O(1)
14+
- ์ƒ์ˆ˜ ๊ณต๊ฐ„๋งŒ ์‚ฌ์šฉ (count, left, right)
15+
16+
ํ’€์ด ๋ฐฉ๋ฒ•:
17+
1. expand_around_center ํ—ฌํผ ํ•จ์ˆ˜:
18+
- ์ฃผ์–ด์ง„ ์ค‘์‹ฌ์—์„œ ์–‘์ชฝ์œผ๋กœ ํ™•์žฅํ•˜๋ฉฐ ํŒฐ๋ฆฐ๋“œ๋กฌ์˜ ๊ฐœ์ˆ˜๋ฅผ ์…ˆ
19+
- ๊ฒฝ๊ณ„ ์ฒดํฌ, ๋ฌธ์ž ์ผ์น˜์—ฌ๋ถ€ ํ™•์ธ
20+
21+
2. ๊ฐ ์œ„์น˜์—์„œ ๋‘ ๊ฐ€์ง€ ๊ฒฝ์šฐ ํ™•์ธ:
22+
- ํ™€์ˆ˜ ๊ธธ์ด: expand_around_center(i, i) - ์ค‘์‹ฌ์ด ํ•œ ๊ธ€์ž
23+
- ์ง์ˆ˜ ๊ธธ์ด: expand_around_center(i, i+1) - ์ค‘์‹ฌ์ด ๋‘ ๊ธ€์ž
24+
25+
ํ•ต์‹ฌ ์•„์ด๋””์–ด:
26+
- ์ค‘์‹ฌ์—์„œ ๋ฐ”๊นฅ์œผ๋กœ ํ™•์žฅ (์•ˆ์—์„œ ๋ฐ–์œผ๋กœ)
27+
- ๋ชจ๋“  ๊ฐ€๋Šฅํ•œ ์ค‘์‹ฌ์ ์—์„œ ํŒฐ๋ฆฐ๋“œ๋กฌ ํƒ์ƒ‰
28+
29+
๋…ธํŠธ:
30+
- dp๋กœ๋„ ํ’€์–ด๋ณด๊ธฐ
31+
"""
32+
# Solution 1: Brute-force
33+
class Solution:
34+
def countSubstrings(self, s: str) -> int:
35+
def isPalindromic(start, end):
36+
while start < end:
37+
if s[start] != s[end]:
38+
return False
39+
start, end = start + 1, end - 1
40+
return True
41+
42+
cnt = 0
43+
44+
for i in range(0, len(s)):
45+
for j in range(i, len(s)):
46+
if isPalindromic(i, j):
47+
cnt += 1
48+
return cnt
49+
50+
# Solution 2
51+
class Solution:
52+
def countSubstrings(self, s: str) -> int:
53+
def expand_around_center(left, right):
54+
cnt = 0
55+
56+
while left >= 0 and right < len(s) and s[left] == s[right]:
57+
cnt += 1
58+
left -= 1
59+
right += 1
60+
return cnt
61+
62+
total = 0
63+
64+
for i in range(len(s)):
65+
# ํ™€์ˆ˜์ผ ๋•Œ
66+
total += expand_around_center(i, i)
67+
# ์ง์ˆ˜์ผ ๋•Œ
68+
total += expand_around_center(i, i+1)
69+
70+
return total
71+

0 commit comments

Comments
ย (0)