Skip to content

Commit 709bccc

Browse files
committed
feat: solved 5
1 parent d7cc258 commit 709bccc

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package com.fghpdf.LongestPalindromicSubstring;
2+
3+
/**
4+
* @author fghpdf
5+
* @date 2019/11/9
6+
* https://leetcode.com/problems/longest-palindromic-substring/
7+
* my way is slow
8+
* discuss has a way to extend to search
9+
*
10+
**/
11+
public class Solution {
12+
public String longestPalindrome(String s) {
13+
if (s.length() == 0) {
14+
return s;
15+
}
16+
17+
int max = 0;
18+
String result = "";
19+
for (int i = s.length() - 1; i >= 0; i--) {
20+
for (int j = 0; j < s.length();j++) {
21+
if (i - j + 1 <= max) {
22+
continue;
23+
}
24+
String sub = s.substring(j, i + 1);
25+
if (isPalindrome(sub)) {
26+
max = sub.length();
27+
result = sub;
28+
}
29+
}
30+
}
31+
return result;
32+
}
33+
34+
private boolean isPalindrome(String s) {
35+
char[] chars = s.toCharArray();
36+
37+
for (int i = 0, j = chars.length - 1; i < j;) {
38+
if (Character.toLowerCase(chars[i++]) != Character.toLowerCase(chars[j--])) {
39+
return false;
40+
}
41+
}
42+
43+
return true;
44+
}
45+
46+
private int lo, maxLen;
47+
48+
private String lo2(String s) {
49+
int len = s.length();
50+
if (len < 2) {
51+
return s;
52+
}
53+
54+
for (int i = 0; i < len-1; i++) {
55+
extendPalindrome(s, i, i); //assume odd length, try to extend Palindrome as possible
56+
extendPalindrome(s, i, i+1); //assume even length.
57+
}
58+
return s.substring(lo, lo + maxLen);
59+
}
60+
61+
private void extendPalindrome(String s, int j, int k) {
62+
System.out.printf("%d %d\n", j, k);
63+
while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) {
64+
j--;
65+
k++;
66+
}
67+
System.out.printf("%d-%d\n", j, k);
68+
if (maxLen < k - j - 1) {
69+
lo = j + 1;
70+
maxLen = k - j - 1;
71+
}
72+
}
73+
74+
75+
76+
public static void main(String[] args) {
77+
Solution sol = new Solution();
78+
System.out.println(sol.lo2("cbbd"));
79+
}
80+
}

0 commit comments

Comments
 (0)