Created
August 12, 2019 01:54
-
-
Save madhur/1eef1ee6eba611a526397c564e35b8d7 to your computer and use it in GitHub Desktop.
longestpalindromic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public String longestPalindrome(String str) { | |
int index1=0; | |
int index2=0; | |
boolean isPalin = true; | |
if(str.length()==0) { | |
return str; | |
} | |
if(str.length()==1) { | |
return str; | |
} | |
int maxLength =0; | |
for(int i=0;i<str.length()-1;++i) { | |
for(int j=i+1; j<str.length(); ++j) { | |
if(isPalin(str, i , j)) { | |
if(j-i > maxLength) { | |
maxLength = j-i; | |
index1 = i; | |
index2 = j; | |
} | |
} | |
} | |
} | |
StringBuilder sb = new StringBuilder(); | |
for(int k=index1; k <= index2; ++k) { | |
sb.append(str.charAt(k)); | |
} | |
System.out.println( str + " " + index1 + " " + index2); | |
return sb.toString(); | |
} | |
private boolean isPalin(String str, int a, int b) { | |
while(a < b) { | |
Character c1 = str.charAt(a); | |
Character c2 = str.charAt(b); | |
if(c1==c2) { | |
a++; | |
b--; | |
} | |
else { | |
return false; | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment