-
Notifications
You must be signed in to change notification settings - Fork 3
/
longest_palindromic_substring.rb
65 lines (56 loc) · 2.02 KB
/
longest_palindromic_substring.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# Longest Palindromic Substring
# Input: Given string :"forgeeksskeegfor",
# Output: "geeksskeeg"
# Input: Given string :"Geeks",
# Output: "ee"
def longest_palindrom(str)
return str if str.length <= 1
result = ''
(0...str.length - 1).each do |i|
((i + 1)...str.length).each do |j|
substr = str[i, j]
result = substr if is_palindrom?(substr) && (result.length < substr.length)
end
end
result
end
def longest_palindrom_dp(str)
length = str.length
return str if length <= 1
result = str[0]
dp = Array.new(length) { |_i| Array.new(length, false) }
(0...length).each do |gap|
(gap...length).each do |j|
if gap.zero?
dp[j - gap][j] = true
elsif gap == 1
if str[j - gap] == str[j]
dp[j - gap][j] = true
result = str[j - gap..j]
end
elsif str[j - gap] == str[j] && dp[j - gap + 1][j - 1]
dp[j - gap][j] = true
result = str[j - gap..j]
end
end
end
result
end
def is_palindrom?(str)
return true if str.length <= 1
i = 0
j = str.length - 1
while i < j
if str[i] == str[j]
i += 1
j -= 1
next
end
return false
end
true
end
puts longest_palindrom_dp('forgeeksskeegfor')
puts longest_palindrom_dp('Geeks')
puts longest_palindrom_dp('bb')
puts longest_palindrom_dp('lphntrsqudccteewsdmpjmgmfnxegawjclzobpnxdrvxeygafiwyqsvsecictqkmiqvrdjajfngvlhdezdpqpzjjzbhoyggrbkuzeocrpzqishvfairdvvabopyubfisxbrgnlughbrzunitwowvnsqhdtnkotitgxwzjhbgltksorygpdberdgzgvogrvwluhixfbrfhliedjylxuspjpitwlhdkneonreqrueqphirmgxtqumllqropaefddplspkrtkbmuvwkyryworojlvwzdlacuoqzokrmcgmwkopsbqjjkaoqjqbrderwzmhbhfgwvrjakyfeqcbtvlcgbsxkngymxyievihiskdmmppmmdksihiveiyxmygnkxsbgclvtbcqefykajrvwgfhbhmzwredrbqjqoakjjqbspokwmgcmrkozqoucaldzwvljorowyrykwvumbktrkpslpddfeaporqllmuqtxgmrihpqeurqernoenkdhlwtipjpsuxlyjdeilhfrbfxihulwvrgovgzgdrebdpgyrosktlgbhjzwxgtitokntdhqsnvwowtinuzrbhgulngrbxsifbuypobavvdriafvhsiqzprcoezukbrggyohbzjjzpqpdzedhlvgnfjajdrvqimkqtcicesvsqywifagyexvrdxnpbozlcjwagexnfmgmjpmdsweetccduqsrtnhpl')