-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongest_substring.py
58 lines (48 loc) · 1.5 KB
/
longest_substring.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
strlen = len(s)
if len(s) <= 1:
return s
dp = [[0 for x in range(strlen)] for y in range(strlen)]
for i in range(strlen):
dp[i][i] = 1
maxlen = 0
maxsub = s[0]
for span in range(1, strlen):
for head in range(0, strlen - span):
#print(strlen - 1 - span)
tail = head + span
#print("span = {}, head = {}, tail = {}".format(span, head, tail))
if span > 1 and dp[head + 1][tail - 1] == 0:
dp[head][tail] = 0
else:
if s[head] == s[tail]:
dp[head][tail] = 1
if span > maxlen:
maxsub = s[head:tail+1]
if len(maxsub) == 0:
return s[0]
return maxsub
def stringToString(input):
return input[1:-1].decode('string_escape')
def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
while True:
try:
line = lines.next()
s = stringToString(line)
ret = Solution().longestPalindrome(s)
out = (ret)
print out
except StopIteration:
break
if __name__ == '__main__':
main()