-
Notifications
You must be signed in to change notification settings - Fork 0
/
5. Longest Palindromic Substring
54 lines (51 loc) · 1.36 KB
/
5. Longest Palindromic Substring
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
** O(n^2)
class Solution {
public String longestPalindrome(String s) {
int start = 0;
int end = 0;
for(int i = 0;i <s.length(); i++)
{
int len1 = expandMiddle(s, i, i);
int len2 = expandMiddle(s, i, i+1);
int len = Math.max(len1, len2);
if(len>end-start)
{
start = i-((len-1)/2);
end = i+(len/2);
}
}
return s.substring(start, end+1);
}
public int expandMiddle(String s, int left, int right)
{
while( left >= 0 && right <s.length() && s.charAt(left) == s.charAt(right))
{
left--;
right++;
}
return right-left-1;
}
}
** Brute force O(n^3)
class Solution {
public String longestPalindrome(String s) {
int len = s.length();
String res = "";
for(int i = 0;i <len; i++)
{
for(int j=i+1; j<=len; j++)
{
String str = s.substring(i,j);
String str1 = "";
int k = str.length()-1;
while(k>=0)
{
str1 = str1 + str.charAt(k);
k--;
}
if(str.equals(str1) && str.length() > res.length()) res = str;
}
}
return res;
}
}