Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
##Brute Force###
public class Solution {
boolean isPalindromic(String s){
int sLen = s.length();
if(sLen == 1)
return true;
for(int i=0; i<sLen/2; i++){
if(s.charAt(i) != s.charAt(sLen-i-1)) // Made a mistake here sLen-i cause overflow.
return false;
}
return true;
}
public String longestPalindrome(String s) {
// Start typing your Java solution below
// DO NOT write main() function
for(int subLen = s.length(); subLen >0; subLen --){
for(int start=0; start <= s.length()-subLen; start++){
String sub = s.substring(start, start+subLen); // Made a mistake without specify the end.
if(isPalindromic(sub))
return sub;
}
}
return null;
}
}
###Dynamic Programming###
public class Solution {
public String longestPalindrome(String s) {
// Start typing your Java solution below
// DO NOT write main() function
int len = s.length();
boolean m[][] = new boolean[len][len];
int max = 0;
int maxStart = 0;
int maxEnd = 0;
for(int l=1; l<=len; l++){
for(int i=0; i<=len-l; i++){
if((l==1)
||(l==2 && s.charAt(i)==s.charAt(i+1) )
||(s.charAt(i)==s.charAt(i+l-1) && m[i+1][i+l-2]) )
{
m[i][i+l-1] = true;
max = l;
maxStart = i;
maxEnd = i+l;
}
}
}
return s.substring(maxStart, maxEnd);
}
}
Bugs encountered:
1. Messed up length of String with its index. (should minus ONE)
2.Forgot to put a end value for the substring.
3.The end value of substring is the index of char following the substring. s.substring(1,2) is the same as s.charAt(1) (except in different type)
------------------------------------------------------------------------------------------------------------------------------------------
LL's solution:
public class Solution {
public String longestPalindrome(String s) {
// Start typing your Java solution below
// DO NOT write main() function
int len = s.length();
if(len==1)
return s;
boolean[][] matrix = new boolean[len+1][len+1];
String sub = null;
int i;
//window = 1
for(i = 0; i<len; i++){
matrix[1][i] = true;
sub = s.substring(i,i+1);
}
//window = 2
for(i = 0; i<len-1; i++)
if(s.charAt(i) == s.charAt(i+1)){
matrix[2][i] = true;
sub = s.substring(i,i+2);
}
//windoe = 3~len
for(int window = 3; window<=len; window++){
for(i = 0; i<=len-window; i++){
if(s.charAt(i) == s.charAt(i+window-1)){
if(matrix[window-2][i+1] == true){
sub = s.substring(i,i+window);
matrix[window][i] = true;
}
}
}
}
return sub;
}
}