Skip to content

Commit

Permalink
add solution: longest palindromic substring
Browse files Browse the repository at this point in the history
  • Loading branch information
obzva committed Nov 17, 2024
1 parent f386b93 commit 575b17e
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions longest-palindromic-substring/flynn.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
ํ’€์ด
- ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ ๊ธฐ๋ฒ•์„ ์ด์šฉํ•˜๋ฉด ํ’€์ดํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค
Big O
- N: ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด s์˜ ๊ธธ์ด
- Time complexity: O(N^2)
- window ํ•จ์ˆ˜๊ฐ€ O(N)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐ€์ง€๋ฏ€๋กœ
๊ฐ ๋ฐ˜๋ณต๋ฌธ์€ O(N * N) = O(N^2)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐ€์ง„๋‹ค๊ณ  ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค
- Space complexity: O(1)
- ๋ณ„๋„์˜ ์ถ”๊ฐ€์ ์ธ ๊ณต๊ฐ„ ๋ณต์žก๋„๋ฅผ ๊ณ ๋ คํ•˜์ง€ ์•Š์•„๋„ ๋ฉ๋‹ˆ๋‹ค
*/

func longestPalindrome(s string) string {
n := len(s)
maxStart := 0
maxEnd := 0
// for odd lengths
for i := 0; i < n; i++ {
window(&s, &maxStart, &maxEnd, i, false)
}
// for even lengths
for i := 0; i < n-1; i++ {
window(&s, &maxStart, &maxEnd, i, true)
}

return s[maxStart : maxEnd+1]
}

/*
helper function for searching palindromic substring
from the pivotal index `i`
*/
func window(s *string, maxStart *int, maxEnd *int, i int, isEven bool) {
n := len(*s)
start := i
end := i
if isEven {
end++
}
for 0 <= start && end < n {
if (*s)[start] != (*s)[end] {
break
}

// if new palindromic substring is longer than the previously found one,
// update the start and end index
if *maxEnd-*maxStart < end-start {
*maxStart = start
*maxEnd = end
}
start--
end++
}
}

0 comments on commit 575b17e

Please sign in to comment.