Skip to content

Commit 575b17e

Browse files
committed
add solution: longest palindromic substring
1 parent f386b93 commit 575b17e

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
풀이
3+
- 슬라이딩 윈도우 기법을 이용하면 풀이할 수 있습니다
4+
Big O
5+
- N: 주어진 문자열 s의 길이
6+
- Time complexity: O(N^2)
7+
- window 함수가 O(N)의 시간복잡도를 가지므로
8+
각 반복문은 O(N * N) = O(N^2)의 시간복잡도를 가진다고 볼 수 있습니다
9+
- Space complexity: O(1)
10+
- 별도의 추가적인 공간 복잡도를 고려하지 않아도 됩니다
11+
*/
12+
13+
func longestPalindrome(s string) string {
14+
n := len(s)
15+
maxStart := 0
16+
maxEnd := 0
17+
// for odd lengths
18+
for i := 0; i < n; i++ {
19+
window(&s, &maxStart, &maxEnd, i, false)
20+
}
21+
// for even lengths
22+
for i := 0; i < n-1; i++ {
23+
window(&s, &maxStart, &maxEnd, i, true)
24+
}
25+
26+
return s[maxStart : maxEnd+1]
27+
}
28+
29+
/*
30+
helper function for searching palindromic substring
31+
from the pivotal index `i`
32+
*/
33+
func window(s *string, maxStart *int, maxEnd *int, i int, isEven bool) {
34+
n := len(*s)
35+
start := i
36+
end := i
37+
if isEven {
38+
end++
39+
}
40+
for 0 <= start && end < n {
41+
if (*s)[start] != (*s)[end] {
42+
break
43+
}
44+
45+
// if new palindromic substring is longer than the previously found one,
46+
// update the start and end index
47+
if *maxEnd-*maxStart < end-start {
48+
*maxStart = start
49+
*maxEnd = end
50+
}
51+
start--
52+
end++
53+
}
54+
}

0 commit comments

Comments
 (0)