I am writing some code to find the longest palindrome in a string. I want to start at index 0 and then push the increasing length of the substring to an array:
ex:
string = "ababa"
[["a", "b"], ["a", "b", "a"], ["a", "b", "a", "b"], ["a", "b", "a", "b", "a"]]
It should then start on index 1 and do the same:
ex:
string = "ababa"
[["b","a"],["b","a","b"],["b","a","b","a"]
This should continue until the index is length -1 .However, the following code stops after it has gone through all iterations beginning with the first index and only returns:
[["a", "b"], ["a", "b", "a"], ["a", "b", "a", "b"], ["a", "b", "a", "b", "a"]]
What is the flaw in my logic? Code below
def longest_palindrome(s)
array = s.chars
start = 0
place = 1
output = []
while start < s.length - 1
while place < s.length
output << array[start..place]
place += 1
end
start += 1
end
return output
end
place
to something likeplace = start + 1
ifstart + 1 < s.length
. Reset outside of the inner while loop, so around where you increment upstart
place
after you incrementstart
. So first dostart += 1
, and then you should doplace = start + 1
if(start + 1) < s.length