-
Notifications
You must be signed in to change notification settings - Fork 214
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1060 from NK-Works/palindromic-substrings
Palindromic Substrings Added
- Loading branch information
Showing
2 changed files
with
25 additions
and
0 deletions.
There are no files selected for viewing
24 changes: 24 additions & 0 deletions
24
...and_Data_Structures/Dynamic-Programming-Series/Hard-DP-Problems/palindromic-substrings.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
def countPalindromicSubstrings(s): | ||
n = len(s) | ||
count = 0 | ||
|
||
def expandAroundCenter(left, right): | ||
nonlocal count | ||
while left >= 0 and right < n and s[left] == s[right]: | ||
count += 1 | ||
left -= 1 | ||
right += 1 | ||
|
||
# Consider each character and each gap between characters as a center | ||
for i in range(n): | ||
expandAroundCenter(i, i) # Odd-length palindromes | ||
expandAroundCenter(i, i + 1) # Even-length palindromes | ||
|
||
return count | ||
|
||
# Test the function | ||
s = "abc" | ||
print(f"Number of palindromic substrings in '{s}': {countPalindromicSubstrings(s)}") | ||
|
||
s = "aaa" | ||
print(f"Number of palindromic substrings in '{s}': {countPalindromicSubstrings(s)}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters