File tree 1 file changed +74
-0
lines changed
longest-palindromic-substring
1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+
3
+ /*
4
+ * Approach 1.
5
+ * time: O(n^3)
6
+ * space: O(1)
7
+ */
8
+ public String longestPalindrome1 (String s ) {
9
+ String longest = "" ;
10
+ for (int i = 0 ; i < s .length (); i ++) {
11
+ for (int j = i ; j < s .length (); j ++) {
12
+ String ss = s .substring (i , j + 1 );
13
+ if (isPalindrome (ss )) {
14
+ if (ss .length () > longest .length ()) {
15
+ longest = ss ;
16
+ }
17
+ }
18
+ }
19
+ }
20
+ return longest ;
21
+ }
22
+
23
+ // Approach 1.
24
+ private boolean isPalindrome (String s ) {
25
+ int left = 0 ;
26
+ int right = s .length () - 1 ;
27
+ while (left < right ) {
28
+ if (s .charAt (left ) != s .charAt (right )) {
29
+ return false ;
30
+ }
31
+ left ++;
32
+ right --;
33
+ }
34
+ return true ;
35
+ }
36
+
37
+ /*
38
+ * Approach 2.
39
+ * time: O(n^2)
40
+ * space: O(1)
41
+ */
42
+ class Solution {
43
+
44
+ public String longestPalindrome (String s ) {
45
+ int maxStart = 0 ;
46
+ int maxEnd = 0 ;
47
+
48
+ for (int i = 0 ; i < s .length (); i ++) {
49
+ int start = i ;
50
+ int end = i ;
51
+ while (0 <= start && end < s .length () && s .charAt (start ) == s .charAt (end )) {
52
+ if (maxEnd - maxStart < end - start ) {
53
+ maxStart = start ;
54
+ maxEnd = end ;
55
+ }
56
+ start --;
57
+ end ++;
58
+ }
59
+
60
+ start = i ;
61
+ end = i + 1 ;
62
+ while (0 <= start && end < s .length () && s .charAt (start ) == s .charAt (end )) {
63
+ if (maxEnd - maxStart < end - start ) {
64
+ maxStart = start ;
65
+ maxEnd = end ;
66
+ }
67
+ start --;
68
+ end ++;
69
+ }
70
+ }
71
+ return s .substring (maxStart , maxEnd + 1 );
72
+ }
73
+ }
74
+ }
You can’t perform that action at this time.
0 commit comments