Wednesday, February 17, 2021

Longest Palindromic Substring

Given a string, find the longest substring which is palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”.


    public static String getPalindromicSubstring(String s, int l, int r) {

while(l>=0 && r<s.length() && s.charAt(l)==s.charAt(r)) {

l--;

r++;

}

return s.substring(l+1, r);

}

public static String longestPalindromicSubstring(String str) {

String longestPalin = "";

for(int i=0; i<str.length()-1; i++) {

String palin = getPalindromicSubstring(str, i, i);

if(palin.length() > longestPalin.length()) {

longestPalin = palin;

}

palin = getPalindromicSubstring(str, i, i+1);

if(palin.length() > longestPalin.length()) {

longestPalin = palin;

}

}

return longestPalin;

}


No comments:

Post a Comment