Skip to content

Commit 5978d27

Browse files
committedDec 26, 2021
Add solution #214
1 parent 59aeb2b commit 5978d27

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy|
6262
203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy|
6363
206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy|
64+
214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard|
6465
217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy|
6566
219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy|
6667
225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy|

‎solutions/0214-shortest-palindrome.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* 214. Shortest Palindrome
3+
* https://leetcode.com/problems/shortest-palindrome/
4+
* Difficulty: Hard
5+
*
6+
* You are given a string s. You can convert s to a palindrome by adding characters
7+
* in front of it.
8+
*
9+
* Return the shortest palindrome you can find by performing this transformation.
10+
*/
11+
12+
/**
13+
* @param {string} s
14+
* @return {string}
15+
*/
16+
var shortestPalindrome = function(s) {
17+
const reversed = s.split('').reverse().join('');
18+
for (let i = s.length; i > 0; i--) {
19+
if (s.slice(0, i) === reversed.slice(s.length - i)) {
20+
return reversed.slice(0, reversed.length - i) + s;
21+
}
22+
}
23+
return '';
24+
};

0 commit comments

Comments
 (0)
Please sign in to comment.