|
| 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