Skip to content

Commit 15a159c

Browse files
committed
add longest palindromic substring solution
1 parent 8fce646 commit 15a159c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
3+
// 시간복잡도: O(N^2)
4+
public String longestPalindrome(String s) {
5+
6+
// 회문 구성 불가 경우
7+
if (s == null || s.length() < 1) {
8+
return "";
9+
}
10+
11+
String result = "";
12+
13+
for (int i = 0; i < s.length(); i++) {
14+
String odd = palindrome(s, i, i);
15+
String even = palindrome(s, i, i + 1);
16+
17+
if (odd.length() > result.length()) {
18+
result = odd;
19+
}
20+
if (even.length() > result.length()) {
21+
result = even;
22+
}
23+
24+
}
25+
26+
return result;
27+
28+
}
29+
30+
private String palindrome(String s, int left, int right) {
31+
32+
// 중앙을 기준으로 좌우 회문 여부 검사
33+
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
34+
left--;
35+
right++;
36+
}
37+
38+
return s.substring(left + 1, right);
39+
}
40+
41+
}
42+

0 commit comments

Comments
 (0)