Skip to content

Commit a338957

Browse files
committed
feat: Add Palindromic Substrings solutions
1 parent bf45649 commit a338957

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

palindromic-substrings/thispath98.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution:
2+
def countSubstrings(self, s: str) -> int:
3+
"""
4+
Intuition:
5+
2중 루프를 돌면서 각 substring에 대해
6+
palindrome인지 아닌지 확인한다.
7+
한번 palindrome인지 확인했으면, set에 추가하여
8+
중복 확인을 한다.
9+
10+
Time Complexity:
11+
O(N^2 x s.length):
12+
2중 루프는 N^2만큼 소요되고,
13+
각 루프에 palindrome을 체크하는 것은
14+
s.length만큼 소요된다.
15+
16+
Space Complexity:
17+
O(N^2):
18+
palindrome이 모두 중복되지 않을 경우 set에
19+
s의 substring 개수만큼 저장한다.
20+
이는 대략 N^2이다.
21+
"""
22+
def is_palindrome(s):
23+
return s == s[::-1]
24+
25+
palindrome_set = set()
26+
answer = 0
27+
for i in range(1, len(s) + 1):
28+
for j in range(0, len(s) - i + 1):
29+
substr = s[j: j + i]
30+
if substr in palindrome_set or is_palindrome(substr):
31+
palindrome_set.add(substr)
32+
answer += 1
33+
return answer

0 commit comments

Comments
 (0)