File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * @lc app=leetcode id=5 lang=java
3+ *
4+ * [5] Longest Palindromic Substring
5+ *
6+ * https://leetcode.com/problems/longest-palindromic-substring/description/
7+ *
8+ * algorithms
9+ * Medium (26.63%)
10+ * Total Accepted: 505.9K
11+ * Total Submissions: 1.9M
12+ * Testcase Example: '"babad"'
13+ *
14+ * Given a string s, find the longest palindromic substring in s. You may
15+ * assume that the maximum length of s is 1000.
16+ *
17+ * Example 1:
18+ *
19+ *
20+ * Input: "babad"
21+ * Output: "bab"
22+ * Note: "aba" is also a valid answer.
23+ *
24+ *
25+ * Example 2:
26+ *
27+ *
28+ * Input: "cbbd"
29+ * Output: "bb"
30+ *
31+ *
32+ */
33+ class Solution {
34+ private int start = 0 ;
35+ private int maxLen = 0 ;
36+
37+ public String longestPalindrome (String s ) {
38+ int len = s .length ();
39+ if (len < 2 ) {
40+ return s ;
41+ }
42+
43+ for (int i = 0 ; i < len - 1 ; i ++) {
44+ extend (s , i , i );
45+ extend (s , i , i +1 );
46+ }
47+
48+ return s .substring (start , start + maxLen );
49+ }
50+
51+ public void extend (String s , int j , int k ) {
52+ while (j >= 0 && k < s .length () && s .charAt (j ) == s .charAt (k )) {
53+ j --;
54+ k ++;
55+ }
56+ if (maxLen < k - j - 1 ) {
57+ maxLen = k - j - 1 ;
58+ start = j + 1 ;
59+ }
60+ }
61+ }
62+
You can’t perform that action at this time.
0 commit comments