Skip to content

Commit 9c262fc

Browse files
committed
Added O(n2) java solution for leetcode 5
1 parent 20fe6a5 commit 9c262fc

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
3+
public static void main(String[] args) {
4+
String s = "abba";
5+
System.out.println(longestPalindromeOn2(s));
6+
}
7+
8+
public static String longestPalindromeOn2(String s) {
9+
10+
if(s == null || s.length() < 1) return "";
11+
12+
int start = 0;
13+
int end = 0;
14+
15+
for(int i = 0; i < s.length(); i++){
16+
int lenOdd = expandFromMiddle(s, i, i);
17+
int lenEven = expandFromMiddle(s, i, i+1);
18+
int lenMax = Math.max(lenOdd, lenEven);
19+
if(lenMax > end - start){
20+
start = i - ((lenMax - 1)/ 2);
21+
end = i + (lenMax/2);
22+
}
23+
}
24+
25+
return s.substring(start, end+1);
26+
27+
}
28+
29+
public static int expandFromMiddle(String s, int left, int right){
30+
31+
if(s == null || left > right) return 0;
32+
33+
while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
34+
left--;
35+
right++;
36+
}
37+
38+
return right - left -1;
39+
40+
}
41+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
Given a string s, return the longest palindromic substring in s.
2+
3+
4+
5+
Example 1:
6+
7+
Input: s = "babad"
8+
Output: "bab"
9+
Explanation: "aba" is also a valid answer.
10+
Example 2:
11+
12+
Input: s = "cbbd"
13+
Output: "bb"
14+
15+
16+
Constraints:
17+
18+
1 <= s.length <= 1000
19+
s consist of only digits and English letters.
20+
21+
Hint:
22+
There are three ways to solve it
23+
1. O(n3) -> for each of all the substring see if its palindrome or not
24+
2. O(n2) -> Expand From middle Approach
25+
3. O(n) -> Manacher's Algorithm -> Very hard

0 commit comments

Comments
 (0)