File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change @@ -215,5 +215,68 @@ public class StringUtil {
215
215
return len;
216
216
}
217
217
218
+
219
+ /**
220
+ * 7、最长回文子串问题。
221
+ * 该解法是扩散法。时间复杂度为O(N * N)。(最优解是马拉车算法,可以优化该题到O(N),不掌握)
222
+ * @param s
223
+ * @return
224
+ */
225
+ public static String longestPalindrome2 (String s ) {
226
+
227
+ if (s. length() == 0 ) {
228
+ return s;
229
+ }
230
+
231
+ // 全局最大回文长度
232
+ int res = 1 ;
233
+ // 全局最大回文长度对应的左位置
234
+ int ll = 0 ;
235
+ // 全局最大回文长度对应的右位置
236
+ int rr = 0 ;
237
+
238
+
239
+ for (int i = 0 ; i < s. length(); i++ ) {
240
+
241
+ // 以i为下标的奇数情况,是否有更大的len来更新res
242
+ int l = i - 1 ;
243
+ int r = i + 1 ;
244
+
245
+ // l和r都在合法范围。且l和r位置字符相等,可以继续扩散
246
+ while (l >= 0 && r < s. length() && s. charAt(l) == s. charAt(r)) {
247
+ int len = (r - l + 1 );
248
+ // 更新最长回文串的长度
249
+ if (len > res) {
250
+ res = len;
251
+ ll = l;
252
+ rr = r;
253
+ }
254
+ // 扩散
255
+ l-- ;
256
+ r++ ;
257
+ }
258
+
259
+ // 以i为下标偶数的情况。是否有更大的len来更新全局res
260
+ l = i;
261
+ r = i + 1 ;
262
+ // l和r都在合法范围。且l和r位置字符相等,可以继续扩散
263
+ while (l >= 0 && r < s. length() && s. charAt(l) == s. charAt(r)) {
264
+ int len = (r - l + 1 );
265
+ // 更新最长回文串的长度
266
+ if (len > res) {
267
+ res = len;
268
+ ll = l;
269
+ rr = r;
270
+ }
271
+ // 扩散
272
+ l-- ;
273
+ r++ ;
274
+ }
275
+
276
+ }
277
+
278
+ return s. substring(ll, rr + 1 );
279
+ }
280
+
218
281
}
219
282
```
You can’t perform that action at this time.
0 commit comments