Skip to content

Commit 3126f4a

Browse files
authored
Create LongestPalidromeSubstring.java
1 parent 44fd301 commit 3126f4a

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Medium/LongestPalidromeSubstring.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Program {
2+
public static String longestPalindromicSubstring(String str) {
3+
4+
int maxLength = 0; int mid = -1;
5+
6+
for(int i=0 ; i<str.length()-1 ; i++){
7+
8+
int oddLength = 0;
9+
10+
if(i>0)
11+
oddLength = findPalindromeLength(str, i, i-1, i+1) +1;
12+
int evenLength = findPalindromeLength(str, i, i, i+1);
13+
14+
int currentLength = Math.max(oddLength, evenLength);
15+
16+
if(currentLength > maxLength){
17+
mid = i;
18+
maxLength = currentLength ;
19+
}
20+
21+
}
22+
23+
boolean isOdd = (maxLength % 2 ) == 1 ;
24+
25+
int maxLeft = isOdd ? mid - maxLength/2 : mid - maxLength/2 + 1 ;
26+
27+
int maxRight = mid+maxLength/2;
28+
29+
if(maxLength == 0) {
30+
return str ;
31+
}
32+
return str.substring(maxLeft, maxRight+1);
33+
34+
}
35+
36+
public static int findPalindromeLength (String str, int middle, int left, int right) {
37+
int length = 0;
38+
39+
while(left >=0 && right <= str.length()-1) {
40+
41+
if( str.charAt(left) == str.charAt(right) ) {
42+
left-- ;
43+
right++ ;
44+
length = length + 2;
45+
} else {
46+
break;
47+
}
48+
49+
}
50+
51+
return length ;
52+
53+
}
54+
55+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy