Skip to content

Commit a1cc869

Browse files
committed
string: add Palindromic Substrings
1 parent 59aea88 commit a1cc869

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

string/palindromic_substrings.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Palindromic Substrings (Medium)
2+
# Link - https://leetcode.com/problems/longest-palindromic-substring/
3+
4+
# Given a string s, return the number of palindromic substrings in it.
5+
6+
# A string is a palindrome when it reads the same backward as forward.
7+
8+
# A substring is a contiguous sequence of characters within the string.
9+
10+
# Example 1:
11+
# Input: s = "abc"
12+
# Output: 3
13+
# Explanation: Three palindromic strings: "a", "b", "c".
14+
15+
16+
class Solution:
17+
def countSubstrings(self, s: str) -> int:
18+
res = 0
19+
20+
def count_palindrome(l, r):
21+
count = 0
22+
while l >= 0 and r < len(s) and s[l] == s[r]:
23+
count += 1
24+
l -= 1
25+
r += 1
26+
return count
27+
28+
for i in range(len(s)):
29+
res += count_palindrome(i, i)
30+
res += count_palindrome(i, i+1)
31+
32+
return res

0 commit comments

Comments
 (0)