Created
May 21, 2023 07:34
-
-
Save codertcet111/aef4692a5e3b74189a9e01aac14f2976 to your computer and use it in GitHub Desktop.
Longest Palindromic Substring problem ruby solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Author: Shubham Mishra | |
| #I/O: puts longest_palindrome("abbdbebffbebshsj") | |
| #O/P: bebffbeb | |
| def longest_palindrome(s) | |
| return s if s.length == 1 | |
| st, en = 0, s.length - 1 | |
| max = 0 | |
| sub_s = "" | |
| sub_s_arr = [] | |
| for i in st..(en - 1) do | |
| for j in (i+1)..en do | |
| if s[i] == s[j] | |
| sub_s_arr << [i,j] | |
| end | |
| end | |
| end | |
| sub_s_arr.sort_by! {|x| -(x[1] - x[0])} | |
| sub_s_arr.each do |ele_i| | |
| i = ele_i[0] | |
| j = ele_i[1] | |
| while i < j && s[i] == s[j] do | |
| i += 1 | |
| j -= 1 | |
| end | |
| if s[i] == s[j] && (j - i == 0 || i - j == 1) | |
| return s[ele_i[0]..ele_i[1]] | |
| end | |
| end | |
| return s[0] | |
| end | |
| puts longest_palindrome("abbdbebffbebshsj") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment