Skip to content

Commit c2224fc

Browse files
committed
feat: week8 - palindromic substrings
1 parent 6c8deca commit c2224fc

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
'''
2+
๋ฐฉ์‹ : Brute-Force
3+
๋ฌธ์ž์— two-pointer๋ฅผ ์ง€์ •ํ•ด์„œ ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ํ™•์ธํ•˜๊ณ 
4+
palindrome์˜ ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜
5+
6+
Time Complexity : O(N^3)
7+
- outer loop(For๋ฌธ) : O(N)
8+
- inner loop(While๋ฌธ) : O(N)
9+
- palindrome ํ™•์ธ์„ ์œ„ํ•ด s[start:end] ์Šฌ๋ผ์ด์‹ฑ ๋ฐ ์—ญ์ˆœ ํ™•์ธ : O(N)
10+
11+
Space Complexity: O(N)
12+
- substring์„ ์ž„์‹œ ์ €์žฅํ•˜๋Š”๋ฐ ๋“œ๋Š” ๊ณต๊ฐ„ ๋น„์šฉ
13+
'''
14+
15+
class Solution:
16+
def countSubstrings(self, s: str) -> int:
17+
cnt = 0
18+
n = len(s)
19+
20+
for start in range(n):
21+
end = n
22+
while start < end:
23+
sub = s[start:end]
24+
if sub == sub[::-1]:
25+
cnt += 1
26+
end -= 1
27+
28+
return cnt
29+
30+
'''
31+
์œ„ ํ’€์ด๋กœ ํ•ด๊ฒฐํ–ˆ์ง€๋งŒ, ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ๋งŽ์ด ๋“œ๋Š” ๊ฒƒ์„ ํŒŒ์•… ํ›„
32+
์•Œ๊ณ ๋‹ฌ๋ ˆ ํ’€์ด 3: Two Pointers ์ดํ•ดํ•˜๊ณ  ์ž‘์„ฑํ•œ ์ฝ”๋“œ
33+
34+
while ๋ฌธ์„ 2ํšŒ๋กœ ๋‚˜๋ˆˆ ์ด์œ ๋Š” aa, baab ํ˜•์‹์˜ ์ง์ˆ˜ palindrome์„ ํŒŒ์•…ํ•˜๊ธฐ ์œ„ํ•จ
35+
์ง์ˆ˜ palindrome์˜ ๊ฒฝ์šฐ ์–‘ ์˜†์˜ ๊ฐ’์ด ๋™์ผํ•ด์•ผ ๊ทธ ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ์ขŒ์šฐ ๊ฐ’์„ ๋น„๊ตํ•ด์„œ ํŒ๋‹จํ•  ์ˆ˜ ์žˆ์Œ
36+
'''
37+
def countSubstrings(s: str) -> int:
38+
cnt = 0
39+
40+
for i in range(0, len(s)):
41+
start, end = i,i
42+
while start >= 0 and end < len(s) and s[start] == s[end]:
43+
cnt += 1
44+
start -=1
45+
end +=1
46+
47+
start, end = i, i+1
48+
while start >= 0 and end < len(s) and s[start] == s[end]:
49+
cnt += 1
50+
start -=1
51+
end +=1
52+
53+
return cnt

0 commit comments

Comments
ย (0)