在其中一个Ruby Game challenges中,要求您找到给定字符串中最长的回文子字符串,因此从abacdfgdcabaypqqpy
中提取ypqqpy
。其中一个[不使用正则表达式]的提交是:
w = string.size
l = (w.to_f / 2).ceil
l.upto(w-1) do |j|
i = w-j
l.upto(w-i+1) do |n|
s = string[n,i]
return s if s == s.reverse
end
end
有人愿意快速了解它是如何运作的吗?
P.S这是一个有效的SO问题吗?
答案 0 :(得分:4)
正如我所说,这不是一个有效的解决方案,例如输入"addaabcd"
(或者回文位于单词的前半部分的任何其他字符串)将失败。一个明显的(虽然效率不高)解决方案可能是:
# iterate over possible palindrom lengths
# (in descending order)
string.size.downto(0) do |n|
# iterate over possible palindrome locations
0.upto(string.size - n) do |i|
# extract the substring
s = string[i,n]
# is the substring a palindrome?
# If yes, we found our solution, because we know
# that no longer palindrome exists
return s if s == s.reverse
end
end
答案 1 :(得分:-1)
一种可能的解决方案
str = "addaabcdaddadcba"
length = str.size
all = [] # contains all possible palindromes of the string
0.upto(length - 2) do |start|
(start+1).upto(length - 1) do |finish|
check_str = str[start,finish] # check each possible substring
next if finish - start == 1 # ignore single letter strings
all.push(check_str) if check_str == check_str.reverse # if the string and its reverse are equal then it is a palindrome
end
end
p all.max_by(&:size)