Skip to content

Commit 0abbbf5

Browse files
committed
Oct 27 Daily LC Longest Palindromic substring
1 parent 0fcd658 commit 0abbbf5

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
Problem Link: https://leetcode.com/problems/longest-palindromic-substring/description/
3+
4+
Problem Statement: Given a string s, return the longest palindromic substring in s.
5+
6+
Solution Approach:
7+
For every index i in the string, have an external function expandfromMiddle to return the longest length of palindrome that
8+
can be formed as this index in the middle.
9+
Also keep in mind two kinds of test cases where palindrome can be of even or odd length.
10+
11+
*/
12+
13+
/* ------------CODE---------------- */
14+
15+
class Solution {
16+
public String longestPalindrome(String s) {
17+
int len = s.length();
18+
if(len<2)
19+
return s;
20+
int start = 0;
21+
int end = 0;
22+
for(int i=0; i<s.length(); i++) {
23+
int len1 = expandFromMiddle(s, i, i); // racecar example, checking for e==e
24+
int len2 = expandFromMiddle(s, i, i+1);
25+
int lenz = Math.max(len1,len2);
26+
if(lenz > end-start) {
27+
start = i - ((lenz-1)/2);
28+
end = i + (lenz/2);
29+
}
30+
}
31+
return s.substring(start, end+1);
32+
}
33+
34+
35+
public int expandFromMiddle(String s, int left, int right) {
36+
if(s==null || left>right)
37+
return 0;
38+
while(left>=0 && right<s.length() && s.charAt(left)==s.charAt(right)) {
39+
left--;
40+
right++;
41+
}
42+
return right-left-1;
43+
}
44+
}
45+
/*
46+
Time Complexity: O(n^2)
47+
Space Complexity: O(1) - we do not need any extra space
48+
*/

0 commit comments

Comments
 (0)