给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。
示例 1:
输入: "babad" 输出: "bab" 注意: "aba"也是一个有效答案。
示例 2:
输入: "cbbd" 输出: "bb"
正确代码:
package LeetCode;
public class A5最长回文子串 {
public String longestPalindrome(String s) {
if (s.length() == 1) {
return s; // 如果就一个字符,返回该字符
}
if (s.length() == 2) { // 如果有两个字符
if (s.charAt(0) == s.charAt(1)) { // 两个字符一样,返回该字符串
return s;
} else { // 两个字符不一样,返回第一个字符
String string = new String();
string += s.charAt(0);
return string;
}
}
int longest = 0; // 当前最长回文长度
String longestString = new String(); // 当前最长回文
for (int i = 1; i < s.length(); i++) {
int temp = 0;
int count = 0; // 当前回文长度
String tempString = new String(); // 当前回文
if (s.charAt(i) == s.charAt(i - 1)) { // 如果多个相同的字符重复
int ii = i + 1;
while (ii < s.length() && s.charAt(i) == s.charAt(ii)) {
temp++;
ii++;
}
count = temp + 2;
if (count > longest) {
longest = count;
while ((count--) != 0) {
tempString += s.charAt(i);
}
longestString = tempString;
}
temp = 0;
count = 0;
tempString = new String();
}
if ((i < s.length() - 1 && s.charAt(i) == s.charAt(i - 1))) { // 以两个字符为中心对称
int iFront = i - 1;
int iBack = i;
while (iFront >= 0 && iBack < s.length() && (s.charAt(iFront) == s.charAt(iBack))) {
temp++;
iFront--;
iBack++;
}
count = temp * 2;
if (count > longest) {
longest = count;
for (int j = i - temp; j < i + temp; j++) {
tempString += s.charAt(j);
}
longestString = tempString;
}
temp = 0;
count = 0;
tempString = new String();
}
//以一个字符为中心对称
int iFront = i - 1;
int iBack = i + 1;
while (iFront >= 0 && iBack < s.length() && (s.charAt(iFront) == s.charAt(iBack))) {
temp++;
iFront--;
iBack++;
}
count = temp * 2 + 1;
if (count > longest) {
longest = count;
for (int j = i - temp; j <= i + temp; j++) {
tempString += s.charAt(j);
}
longestString = tempString;
}
}
System.out.println(longest);
return longestString;
}
public static void main(String[] args) {
A5最长回文子串 a5最长回文子串 = new A5最长回文子串();
String s1 = new String("babad");
String s2 = new String(
"azwdzwmwcqzgcobeeiphemqbjtxzwkhiqpbrprocbppbxrnsxnwgikiaqutwpftbiinlnpyqstkiqzbggcsdzzjbrkfmhgtnbujzszxsycmvipjtktpebaafycngqasbbhxaeawwmkjcziybxowkaibqnndcjbsoehtamhspnidjylyisiaewmypfyiqtwlmejkpzlieolfdjnxntonnzfgcqlcfpoxcwqctalwrgwhvqvtrpwemxhirpgizjffqgntsmvzldpjfijdncexbwtxnmbnoykxshkqbounzrewkpqjxocvaufnhunsmsazgibxedtopnccriwcfzeomsrrangufkjfzipkmwfbmkarnyyrgdsooosgqlkzvorrrsaveuoxjeajvbdpgxlcrtqomliphnlehgrzgwujogxteyulphhuhwyoyvcxqatfkboahfqhjgujcaapoyqtsdqfwnijlkknuralezqmcryvkankszmzpgqutojoyzsnyfwsyeqqzrlhzbc");
System.out.println(a5最长回文子串.longestPalindrome(s2));
}
}
这道题要考虑的东西比较多。
a:a
aa:aa
aa:aa
ab:a
aaa:aaa
ababd:aba/bab
abaccaba:abac
abaccaba:abac