-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
chenzhengwei
committed
May 16, 2017
1 parent
0abb3f6
commit e7d18f4
Showing
2 changed files
with
36 additions
and
0 deletions.
There are no files selected for viewing
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
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,34 @@ | ||
#5. Longest Palindromic Substring | ||
[题目链接](https://leetcode.com/problems/longest-palindromic-substring/#/description) | ||
```python | ||
class Solution(object): | ||
start = maxLength = 0 | ||
def findPalindrome(self, s, i, j): | ||
""" | ||
:param s: str | ||
:param i: int | ||
:param j: int | ||
:return: | ||
""" | ||
while i >= 0 and j < len(s) and s[i] == s[j]: | ||
i -= 1 | ||
j += 1 | ||
length = j - i - 1 | ||
if length > self.maxLength: | ||
self.maxLength = length | ||
self.start = i + 1 | ||
|
||
def longestPalindrome(self, s): | ||
""" | ||
:type s: str | ||
:rtype: str | ||
""" | ||
if len(s) <= 2: | ||
return s | ||
# 遍历字符串计算,分奇数情况和偶数情况 | ||
for i in range(len(s)): | ||
self.findPalindrome(s, i, i) | ||
self.findPalindrome(s, i, i + 1) | ||
return s[self.start: self.start + self.maxLength] | ||
|
||
``` |