java 暴力解法
class Solution {
public String longestPalindrome(String s) {
int N = s.length();
if(N <= 1) return s;
for(int i = N; i > 0; i--){
for(int j = 0; j <= N-i; j++){
String substr = s.substring(j, j+i);
if(isPalindrom(substr)) return substr;
}
}
return s.substring(0,1);
}
public boolean isPalindrom(String s){
if(s.length() <= 1){
return false;
}
int l = 0, r = s.length() - 1;
while(l < r){
if(s.charAt(l) != s.charAt(r)){
return false;
}
l++;
r--;
}
return true;
}
}
从中心向两边扩散,分奇偶两种情况
class Solution {
public String longestPalindrome(String s) {
int len = s.length();
String res = "";
for(int i = 0; i < len; i++){
int l = i - 1, r = i + 1;
while(l>=0 && r<len && s.charAt(l) == s.charAt(r)){l--;r++;}
if(res.length() < r - l - 1) res = s.substring(l+1, r);
l = i; r = i + 1;
while(l>=0 && r<len && s.charAt(l) == s.charAt(r)){l--;r++;}
if(res.length() < r - l - 1) res = s.substring(l+1, r);
}
return res;
}
}
notability还可以做有颜色的框框!
这字真的好看