-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode-longest_palindromic_substring.rb
57 lines (44 loc) · 1.9 KB
/
leetcode-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
def longest_palindrome(s)
palindrome = ''
letters = s.chars
letters.each_with_index { |l, i|
n = 0
l_size = letters.size
while l_size > 1
l_range = letters[i...(letters.size - n)]
palindrome = l_range.join if l_range == l_range.reverse && l_range.size > palindrome.length
n += 1
l_size = letters[i...(letters.size - n)].size
break if l_size <= palindrome.length
end
}
p palindrome.empty? ? palindrome = s[0] : palindrome
end
## TEST
s_a = 'babad'
puts "\n String A:"
longest_palindrome(s_a)
# Output: "bab"
s_b = 'cbbd'
puts "\n String B:"
longest_palindrome(s_b)
# Output: "bb"
s_c = 'cbbdtepipetsqsrv'
puts "\n String C:"
longest_palindrome(s_c)
# Output: "tepipet"
s_d = 'a'
puts "\n String D:"
longest_palindrome(s_d)
# Output: "a"
s_e = 'ac'
puts "\n String E:"
longest_palindrome(s_e)
# Output: "a"
s_f = 'bb'
puts "\n String F:"
longest_palindrome(s_f)
# Output: "bb"
s_g = 'zudfweormatjycujjirzjpyrmaxurectxrtqedmmgergwdvjmjtstdhcihacqnothgttgqfywcpgnuvwglvfiuxteopoyizgehkwuvvkqxbnufkcbodlhdmbqyghkojrgokpwdhtdrwmvdegwycecrgjvuexlguayzcammupgeskrvpthrmwqaqsdcgycdupykppiyhwzwcplivjnnvwhqkkxildtyjltklcokcrgqnnwzzeuqioyahqpuskkpbxhvzvqyhlegmoviogzwuiqahiouhnecjwysmtarjjdjqdrkljawzasriouuiqkcwwqsxifbndjmyprdozhwaoibpqrthpcjphgsfbeqrqqoqiqqdicvybzxhklehzzapbvcyleljawowluqgxxwlrymzojshlwkmzwpixgfjljkmwdtjeabgyrpbqyyykmoaqdambpkyyvukalbrzoyoufjqeftniddsfqnilxlplselqatdgjziphvrbokofvuerpsvqmzakbyzxtxvyanvjpfyvyiivqusfrsufjanmfibgrkwtiuoykiavpbqeyfsuteuxxjiyxvlvgmehycdvxdorpepmsinvmyzeqeiikajopqedyopirmhymozernxzaueljjrhcsofwyddkpnvcvzixdjknikyhzmstvbducjcoyoeoaqruuewclzqqqxzpgykrkygxnmlsrjudoaejxkipkgmcoqtxhelvsizgdwdyjwuumazxfstoaxeqqxoqezakdqjwpkrbldpcbbxexquqrznavcrprnydufsidakvrpuzgfisdxreldbqfizngtrilnbqboxwmwienlkmmiuifrvytukcqcpeqdwwucymgvyrektsnfijdcdoawbcwkkjkqwzffnuqituihjaklvthulmcjrhqcyzvekzqlxgddjoir'
puts "\n String G:"
longest_palindrome(s_g)