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

171人阅读 评论(0)

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;

}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：18901次
• 积分：950
• 等级：
• 排名：千里之外
• 原创：79篇
• 转载：5篇
• 译文：0篇
• 评论：2条
评论排行