File tree 1 file changed +32
-2
lines changed
longest-palindromic-substring
1 file changed +32
-2
lines changed Original file line number Diff line number Diff line change @@ -35,8 +35,8 @@ private boolean isPalindrome(String s) {
35
35
}
36
36
37
37
/*
38
- * Approach 2.
39
- * time: O(n^2)
38
+ * Approach 2-1 .
39
+ * time: ์๊ฐ ๋ณต์ก๋๋ ํ๊ท ์ ์ผ๋ก O(n)์ด๊ณ , palindrome ์ ๊ธธ์ด๊ฐ n ์ ๊ฐ๊น์์ง๋ฉด ์๊ฐ ๋ณต์ก๋ ์ญ์ O(n ^2) ์ ๊ฐ๊น์ ์ง๋ค.
40
40
* space: O(1)
41
41
*/
42
42
class Solution {
@@ -71,4 +71,34 @@ public String longestPalindrome(String s) {
71
71
return s .substring (maxStart , maxEnd + 1 );
72
72
}
73
73
}
74
+
75
+ /*
76
+ * Approach 2-2.
77
+ * time: ์๊ฐ ๋ณต์ก๋๋ ํ๊ท ์ ์ผ๋ก O(n)์ด๊ณ , palindrome ์ ๊ธธ์ด๊ฐ n ์ ๊ฐ๊น์์ง๋ฉด ์๊ฐ ๋ณต์ก๋ ์ญ์ O(n^2) ์ ๊ฐ๊น์ ์ง๋ค.
78
+ * space: O(1)
79
+ */
80
+ class Solution {
81
+ int maxStart = 0 ;
82
+ int maxEnd = 0 ;
83
+
84
+ public String longestPalindrome (String s ) {
85
+ for (int i = 0 ; i < s .length (); i ++) {
86
+ calculateMaxLength (i , i , s );
87
+ calculateMaxLength (i , i +1 , s );
88
+ }
89
+ return s .substring (maxStart , maxEnd + 1 );
90
+ }
91
+
92
+ public void calculateMaxLength (int start , int end , String s ){
93
+ while (start >= 0 && end < s .length () && s .charAt (start ) == s .charAt (end )) {
94
+ if (this .maxEnd - this .maxStart < end - start ) {
95
+ this .maxStart = start ;
96
+ this .maxEnd = end ;
97
+ }
98
+ start --;
99
+ end ++;
100
+ }
101
+ }
102
+
103
+ }
74
104
}
You canโt perform that action at this time.
0 commit comments