add new solutions
This commit is contained in:
parent
9c2c959a9b
commit
9a10695e8c
29 changed files with 1074 additions and 2 deletions
37
solutions/0/q5/solution.go
Normal file
37
solutions/0/q5/solution.go
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
package q5
|
||||
|
||||
// Note: Although it can be done in O(N) with, e.g., Manacher's algorithm, the
|
||||
// input size is small enough to brute-force.
|
||||
|
||||
func expand(s string, l, r int) (int, int) {
|
||||
for l > 0 && r < len(s)-1 && s[l-1] == s[r+1] {
|
||||
l--
|
||||
r++
|
||||
}
|
||||
return l, r
|
||||
}
|
||||
|
||||
func longestPalindrome(s string) string {
|
||||
maxLen, mL, mR := 0, 0, 0
|
||||
|
||||
for c := range len(s) {
|
||||
l, r := expand(s, c, c)
|
||||
len_ := r - l + 1
|
||||
if len_ > maxLen {
|
||||
maxLen, mL, mR = len_, l, r
|
||||
}
|
||||
}
|
||||
|
||||
for c := range len(s) - 1 {
|
||||
if s[c] == s[c+1] {
|
||||
l, r := expand(s, c, c+1)
|
||||
len_ := r - l + 1
|
||||
if len_ > maxLen {
|
||||
maxLen, mL, mR = len_, l, r
|
||||
}
|
||||
}
|
||||
}
|
||||
return s[mL : mR+1]
|
||||
}
|
||||
|
||||
var _ = longestPalindrome
|
||||
Loading…
Add table
Add a link
Reference in a new issue