-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path336_palindrome_pairs.rb
49 lines (35 loc) · 1.05 KB
/
336_palindrome_pairs.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# frozen_string_literal: true
# https://leetcode.com/problems/palindrome-pairs/
# @param {String[]} words
# @return {Integer[][]}
def palindrome_pairs(words)
result = []
word_map = words.each_with_index.to_h
words.each_with_index do |word, index|
valid_prefixes, valid_suffixes = get_partials(word)
valid_prefixes.each do |prefix|
reverse = prefix.reverse
next unless word_map[reverse] && index != word_map[reverse]
result << [index, word_map[reverse]]
end
valid_suffixes.each do |suffix|
reverse = suffix.reverse
result << [word_map[reverse], index] if word_map[reverse] && index != word_map[reverse]
end
end
result.uniq
end
private
# @param {String} word
# @return {Integer[]}
def get_partials(word)
valid_prefixes = []
valid_suffixes = []
(0..word.length).each do |i|
prefix = word.slice(0, i)
suffix = word.slice(i, word.size)
valid_prefixes << prefix if suffix == suffix.reverse
valid_suffixes << suffix if prefix == prefix.reverse
end
[valid_prefixes, valid_suffixes]
end