Skip to content

Commit 2d6f0ec

Browse files
committed
Implement is_substring_palindrome using dynamic programming.
1 parent 3c40fda commit 2d6f0ec

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

strings/is_substring_palindrome.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
MAX_LEN = 1000
2+
3+
text = ""
4+
dp = [[False for i in range(MAX_LEN)] for i in range(MAX_LEN)]
5+
6+
def preprocess(s):
7+
"""
8+
Preprocesses a string using dynamic programming.
9+
Time complexity: O(n^2)
10+
"""
11+
global text
12+
global dp
13+
text = s
14+
dp = [[False for i in range(MAX_LEN)] for i in range(MAX_LEN)]
15+
n = len(s)
16+
17+
for i in range(n):
18+
dp[i][i] = True
19+
20+
for i in range(n - 1):
21+
dp[i][i + 1] = (text[i] == text[i + 1])
22+
23+
for substr_len in range(2, n + 1):
24+
for i in range(n - substr_len + 1):
25+
j = i + substr_len - 1
26+
dp[i][j] = (text[i] == text[j] and dp[i + 1][j - 1])
27+
28+
29+
def is_substring_palindrome(l, r):
30+
"""
31+
Returns True if and only if the substring text[l:r] is a palindrome.
32+
Time complexity: O(1)
33+
Call preprocess function at least once, before calling this function.
34+
"""
35+
n = len(text)
36+
if l >= r or l < 0 or r > n:
37+
return False
38+
else:
39+
return dp[l][r - 1]
40+
41+
42+
if __name__ == '__main__':
43+
s = "'nursesrun' and 'racecar' are some palindromes."
44+
45+
preprocess(s)
46+
47+
# Answering some queries:
48+
if is_substring_palindrome(1, 10):
49+
print(s[1:10], "is a palindrome.")
50+
else:
51+
print(s[1:10], "is not a palindrome.")
52+
53+
if is_substring_palindrome(17, 24):
54+
print(s[17:24], "is a palindrome.")
55+
else:
56+
print(s[17:24], "is not a palindrome.")
57+
58+
if is_substring_palindrome(35, 45):
59+
print(s[35:45], "is a palindrome.")
60+
else:
61+
print(s[35:45], "is not a palindrome.")

0 commit comments

Comments
 (0)