您的位置:首页 > 其它

leedcode做题总结, 题目Longest Palindromic Substring 5

2015-01-25 06:46 447 查看
题目是求一个字符串的最长回文子串,可以用两种方法,一种是动态规划,用一个矩阵,boolean[i,j] 表示字符串从i-j是否为一个回文串,我用的方法是直接判断,DP方法见http://www.cnblogs.com/dollarzhaole/archive/2013/07/22/3207364.html

class Solution11 {
public String longestPalindrome(String input) {
int max=0;
String res="";
for(int i=0;i<input.length();i++){
int j=0;
int tmp=1;
while(++j>0){
if((i-j)>=0 && (i+j)<input.length() && input.charAt(i-j)==input.charAt(i+j))
tmp += 2;
else
break;
}
if(tmp>max){
max = tmp;
res = input.substring(i-j+1,i+j);
}
if(i+1<input.length()&&input.charAt(i)==input.charAt(i+1)){
j=0;
tmp=2;
while(++j>0){
if((i-j)>=0 && (i+1+j)<input.length() && input.charAt(i-j)==input.charAt(i+j+1))
tmp += 2;
else
break;
}
if(tmp>max){
max = tmp;
res = input.substring(i-j+1,i+j+1);
}

}
}
return res;
}
}


Update 2015/09/01: 下面是九章的解法,和上面的差不多

public class Solution {
/**
* @param s input string
* @return the longest palindromic substring
*/
public String longestPalindrome(String s) {
// Write your code here
if (s == null || s.length() == 0) {
return "";
}

int length = s.length();
int max = 0;
String result = "";
for(int i = 1; i <= 2 * length - 1; i++){
int count = 1;
while(i - count >= 0 && i + count <= 2 * length  && get(s, i - count) == get(s, i + count)){
count++;
}
count--; // there will be one extra count for the outbound #
if(count > max) {
result = s.substring((i - count) / 2, (i + count) / 2);
max = count;
}
}

return result;
}
private char get(String s, int i) {
if(i % 2 == 0)
return '#';
else
return s.charAt(i / 2);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: