File tree 1 file changed +30
-0
lines changed
1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ def count_same_first_last_char_substrings(s):
2
+ n = len(s)
3
+ count = 0
4
+
5
+ # Create a table to store the counts of substrings
6
+ dp = [[0] * n for _ in range(n)]
7
+
8
+ # All substrings of length 1 have the same first and last character
9
+ for i in range(n):
10
+ dp[i][i] = 1
11
+ count += 1
12
+
13
+ # Check substrings of length 2 and more
14
+ for length in range(2, n + 1):
15
+ for start in range(n - length + 1):
16
+ end = start + length - 1
17
+
18
+ # Check if the first and last characters are the same
19
+ if s[start] == s[end]:
20
+ # If it's a two-character substring, or if the inner substring is a palindrome
21
+ if length == 2 or dp[start + 1][end - 1] == length - 2:
22
+ dp[start][end] = length
23
+ count += 1
24
+
25
+ return count
26
+
27
+ # Example usage:
28
+ input_string = "abba"
29
+ result = count_same_first_last_char_substrings(input_string)
30
+ print(f"The number of substrings with the same first and last characters is: {result}")
You can’t perform that action at this time.
0 commit comments