File tree Expand file tree Collapse file tree 1 file changed +32
-2
lines changed
longest-palindromic-substring Expand file tree Collapse file tree 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) {
3535 }
3636
3737 /*
38- * Approach 2.
39- * time: O(n^2)
38+ * Approach 2-1 .
39+ * time: ์๊ฐ ๋ณต์ก๋๋ ํ๊ท ์ ์ผ๋ก O(n)์ด๊ณ , palindrome ์ ๊ธธ์ด๊ฐ n ์ ๊ฐ๊น์์ง๋ฉด ์๊ฐ ๋ณต์ก๋ ์ญ์ O(n ^2) ์ ๊ฐ๊น์ ์ง๋ค.
4040 * space: O(1)
4141 */
4242 class Solution {
@@ -71,4 +71,34 @@ public String longestPalindrome(String s) {
7171 return s .substring (maxStart , maxEnd + 1 );
7272 }
7373 }
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+ }
74104}
You canโt perform that action at this time.
0 commit comments