Skip to content

Commit 2af103e

Browse files
committed
Add solution #336
1 parent 43dc4e3 commit 2af103e

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,7 @@
271271
332|[Reconstruct Itinerary](./0332-reconstruct-itinerary.js)|Hard|
272272
334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium|
273273
335|[Self Crossing](./0335-self-crossing.js)|Hard|
274+
336|[Palindrome Pairs](./0336-palindrome-pairs.js)|Hard|
274275
337|[House Robber III](./0337-house-robber-iii.js)|Medium|
275276
338|[Counting Bits](./0338-counting-bits.js)|Easy|
276277
341|[Flatten Nested List Iterator](./0341-flatten-nested-list-iterator.js)|Medium|

solutions/0336-palindrome-pairs.js

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* 336. Palindrome Pairs
3+
* https://leetcode.com/problems/palindrome-pairs/
4+
* Difficulty: Hard
5+
*
6+
* You are given a 0-indexed array of unique strings words.
7+
*
8+
* A palindrome pair is a pair of integers (i, j) such that:
9+
* - 0 <= i, j < words.length,
10+
* - i != j, and
11+
* - words[i] + words[j] (the concatenation of the two strings) is a palindrome.
12+
*
13+
* Return an array of all the palindrome pairs of words.
14+
*
15+
* You must write an algorithm with O(sum of words[i].length) runtime complexity.
16+
*/
17+
18+
/**
19+
* @param {string[]} words
20+
* @return {number[][]}
21+
*/
22+
var palindromePairs = function(words) {
23+
const result = [];
24+
const map = new Map();
25+
const rMap = new Map();
26+
27+
words.forEach((word, i) => {
28+
map.set(word, i);
29+
rMap.set(word.split('').reverse().join(''), i);
30+
});
31+
32+
words.forEach((word, i) => {
33+
for (let j = 0; j <= word.length; j++) {
34+
if (isPalindrome(word, 0, j - 1)) {
35+
const right = word.slice(j);
36+
if (rMap.has(right) && rMap.get(right) !== i) {
37+
result.push([rMap.get(right), i]);
38+
}
39+
}
40+
if (j < word.length && isPalindrome(word, j, word.length - 1)) {
41+
const left = word.slice(0, j);
42+
if (rMap.has(left) && rMap.get(left) !== i) {
43+
result.push([i, rMap.get(left)]);
44+
}
45+
}
46+
}
47+
});
48+
49+
return result;
50+
51+
function isPalindrome(s, start, end) {
52+
while (start < end) {
53+
if (s[start++] !== s[end--]) return false;
54+
}
55+
return true;
56+
}
57+
};

0 commit comments

Comments
 (0)