Created
April 9, 2024 15:37
-
-
Save preston-56/3d257e1fb09ca56f53aa900f21677928 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| # Given a string s, return the number of palindromic substrings in it. | |
| # A string is a palindrome when it reads the same backward as forward. | |
| # A substring is a contiguous sequence of characters within the string. | |
| def countSubsring(s): | |
| """ | |
| :type s: str | |
| :rtype: int | |
| """ | |
| count = 0 | |
| def count_palindromes(left, right): | |
| local_count = 0 | |
| while left >= 0 and right < len(s) and s[left] == s[right]: | |
| local_count += 1 | |
| left -= 1 | |
| right += 1 | |
| return local_count | |
| for i in range(len(s)): | |
| count += count_palindromes(i, i) | |
| count += count_palindromes(i, i + 1) | |
| return count | |
| s1 = "abc" | |
| s2 = "aaa" | |
| # Test cases | |
| print(countSubsring(s1)) # # Output: 3 | |
| print(countSubsring(s2)) # Output: 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment