# Longest Palindromic Substring --leetcode 数据结构第五题

Subscribe to see which companies asked this question

public String longestPalindrome(String s) {
String resultStr = "";
for (int i = 0; i < s.length(); i++) {
for (int j = i + resultStr.length(); j < s.length() + 1; j++) {
String temp=s.substring(i, j);
StringBuffer tempStr = new StringBuffer(temp);
tempStr = tempStr.reverse();
if (temp.equals(tempStr.toString())) {
if(tempStr.length()>resultStr.length()){
resultStr=tempStr.toString();
}
}
}
}
return resultStr;
}


public String longestPalindrome(String s) {
if (s.isEmpty()) {
return null;
}
if (s.length() == 1) {
return s;
}
String longest = s.substring(0, 1);
for (int i = 0; i < s.length(); i++) {
// get longest palindrome with center of i
String tmp = helper(s, i, i);
if (tmp.length() > longest.length()) {
longest = tmp;
}

// get longest palindrome with center of i, i+1
tmp = helper(s, i, i + 1);
if (tmp.length() > longest.length()) {
longest = tmp;
}
}
return longest;
}

// Given a center, either one letter or two letter,
// Find longest palindrome
public static String helper(String s, int begin, int end) {
while (begin >= 0 && end <= s.length() - 1
&& s.charAt(begin) == s.charAt(end)) {
begin--;
end++;
}
String subS = s.substring(begin + 1, end);
return subS;

}

#### LeetCode第五题，Longest Palindromic Substring

2014-08-05 14:29:41

#### Python 刷题日记：LeetCode 5&9&516- Longest Palindromic Substring 题集合

2017-06-25 20:40:45

#### [LeetCode]5 Longest Palindromic Substring(C++，Python实现)

2014-05-23 21:28:36

#### LeetCode(5) Longest Palindromic Substring

2013-11-27 14:00:30

#### LeetCode Longest Palindromic Substring 最长回文子字符串 两种方法分析解答

2013-11-23 10:27:57

#### LeetCode 5. Longest Palindromic Substring 最长回文子串 Python 四种解法(Manacher 动态规划)

2018-01-06 11:41:46

#### [leetcode: Python]5.Longest Palindromic Substring

2017-05-17 10:32:45

#### LeetCode 5 Longest Palindromic Substring(C,C++,Python,Java)

2015-05-06 15:38:22

#### LeetCode5——Longest Palindromic Substring 最易懂的解法

2016-01-22 23:05:18

#### LeetCode 5:Longest Palindromic Substring

2015-05-12 00:38:14