Skip to content

Commit 8694d0a

Browse files
committed
shortest_palindrome
1 parent 28fe57e commit 8694d0a

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
171171
#### [210. Course Schedule II](https://github.com/hitzzc/go-leetcode/tree/master/course_schedule_II)
172172
#### [211. Add and Search Word - Data structure design](https://github.com/hitzzc/go-leetcode/tree/master/add_and_search_word)
173173
#### [213. House Robber II](https://github.com/hitzzc/go-leetcode/tree/master/add_and_search_word)
174+
#### [214. Shortest Palindrome (unsolved)](https://github.com/hitzzc/go-leetcode/tree/master/shortest_palindrome)
174175

175176

176177

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package shortest_palindrome
2+
3+
func shortestPalindrome(s string) string {
4+
matrix := make([][]bool, len(s))
5+
for i := range matrix {
6+
matrix[i] = make([]bool, len(s))
7+
}
8+
for i := len(matrix) - 1; i >= 0; i-- {
9+
for j := i; j < len(matrix[i]); j++ {
10+
if j == i || s[i] == s[j] && (i+1 == j || matrix[i+1][j-1]) {
11+
matrix[i][j] = true
12+
}
13+
}
14+
}
15+
16+
p := len(s) - 1
17+
for ; p >= 0; p-- {
18+
if matrix[0][p] {
19+
break
20+
}
21+
}
22+
return reverse(s[p+1:]) + s
23+
}
24+
25+
func reverse(s string) string {
26+
bytes := make([]byte, len(s))
27+
for i := range s {
28+
bytes[len(s)-i-1] = s[i]
29+
}
30+
return string(bytes)
31+
}

0 commit comments

Comments
 (0)