Skip to content

Commit 5a30974

Browse files
committed
feat(LeetCode): ✨ add shortestPalindrome (lc. 0214)
1 parent 428c95c commit 5a30974

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { shortestPalindrome } from './0214-shortestPalindrome'
2+
3+
it.each(
4+
// prettier-ignore
5+
[
6+
[
7+
"aacecaaa",
8+
"aaacecaaa"
9+
],
10+
[
11+
"abcd",
12+
"dcbabcd"
13+
]
14+
]
15+
)('should work %#', (input, output) => {
16+
expect(shortestPalindrome(input)).toBe(output)
17+
})
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* {@link https://leetcode.com/problems/shortest-palindrome/ | 214. Shortest Palindrome}
3+
*
4+
* Topics: String | Rolling Hash | String Matching | Hash Function
5+
*
6+
* Brute Force
7+
*/
8+
export function shortestPalindrome(s: string): string {
9+
if (!s || s.length === 1) return s
10+
11+
const isPalindrome = (s: string) => {
12+
let [i, j] = [0, s.length - 1]
13+
14+
while (i <= j) {
15+
if (s[i++] !== s[j--]) return false
16+
}
17+
18+
return true
19+
}
20+
21+
const reverseString = [...s].reverse().join('')
22+
for (let i = 0; i < reverseString.length; i++) {
23+
const res = reverseString.slice(0, i) + s
24+
if (isPalindrome(res)) return res
25+
}
26+
27+
return ''
28+
}

0 commit comments

Comments
 (0)