Skip to content

Commit de43128

Browse files
committed
palindromic-substrings sol (py)
1 parent 83ce8a4 commit de43128

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

โ€Žpalindromic-substrings/hi-rachel.pyโ€Ž

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,38 @@ def countSubstrings(self, s: str) -> int:
5555
cnt += 1
5656

5757
return cnt
58+
59+
60+
# 25/09/08 ๋ณต์Šต
61+
62+
"""
63+
โ€œ๋ชจ๋“  ํšŒ๋ฌธ์€ ์ค‘์‹ฌ์—์„œ ์ขŒ์šฐ ๋Œ€์นญ์ด๋‹คโ€
64+
โ†’ ๋”ฐ๋ผ์„œ ๋ชจ๋“  ์ค‘์‹ฌ์ ์—์„œ ์ขŒ์šฐ๋กœ ํ™•์žฅํ•˜๋ฉด์„œ ํšŒ๋ฌธ์ธ์ง€ ํ™•์ธํ•˜๋ฉด
65+
โ†’ ๋ชจ๋“  ํšŒ๋ฌธ substring์„ ํƒ์ƒ‰ ๊ฐ€๋Šฅ!
66+
67+
- ์ค‘์‹ฌ์ ์˜ ๊ฐœ์ˆ˜๋Š” ์ด 2n - 1๊ฐœ:
68+
- ํ™€์ˆ˜ ๊ธธ์ด: center = 0 ~ n-1 (expand(i, i))
69+
- ์ง์ˆ˜ ๊ธธ์ด: center = 0 ~ n-1 (expand(i, i+1))
70+
71+
TC: O(N^2)
72+
SC: O(1)
73+
"""
74+
75+
class Solution:
76+
def countSubstrings(self, s: str) -> int:
77+
count = 0
78+
for center in range(len(s)):
79+
print(center)
80+
count += self.expand(s, center, center)
81+
82+
count += self.expand(s, center, center + 1)
83+
return count
84+
85+
def expand(self, s, left, right):
86+
count = 0
87+
# ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜์ง€ ์•Š๊ณ , palindrome์ด๋ฉด ํ™•์žฅ
88+
while left >= 0 and right < len(s) and s[left] == s[right]:
89+
count += 1
90+
left -= 1
91+
right += 1
92+
return count

0 commit comments

Comments
ย (0)