Ruby 此代码段如何从字符串中找到回文子字符串?
在其中一个示例中,要求您查找给定字符串中最长的回文子字符串,因此从Ruby 此代码段如何从字符串中找到回文子字符串?,ruby,Ruby,在其中一个示例中,要求您查找给定字符串中最长的回文子字符串,因此从abacdfgdcabaypqpy中,您应该提取ypqpy。其中一份[不使用正则表达式]的提交是: 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 有人愿意简要介绍一下它的工作原
abacdfgdcabaypqpy
中,您应该提取ypqpy
。其中一份[不使用正则表达式]的提交是:
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问题吗?正如我所说,这不是一个有效的解决方案,例如输入
“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
正如我所说,这不是一个有效的解决方案,例如输入
“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
一个可能的解决办法
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)
一个可能的解决办法
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)
问题是,此代码不正确。对于像
“addaabcd”
这样的输入,它会失败,因为回文位于前半部分。解释它没有意义,但如果你想的话,我可以把一些没有正则表达式的代码拼凑在一起,并给出解释。问题是,这些代码是不正确的。对于像“addaabcd”
这样的输入,它会失败,因为回文位于前半部分。解释它没有意义,但是如果你想,我可以把一些没有正则表达式的代码拼凑起来,并附上一个解释。此外,这段代码有一个错误:它应该是str[start..finish],而不是str[start,finish],因为后者从start开始使用“finish”字符数。此外,这段代码有一个错误:它应该是str[start..finish],not str[start,finish],因为后者使用“finish”开头的字符数。正则表达式无法找到以字符串前面较短回文中包含的字母开头的回文。示例:“ppop”=>“pp”
@Lars:抓得好!重点是,在许多语言中,回文可以与正则表达式匹配,尽管回文的语言不是规则的。但这似乎是一个坏例子:)正则表达式无法找到以字符串前面较短回文中包含的字母开头的回文。示例:“ppop”=>“pp”
@Lars:抓得好!重点是,在许多语言中,回文可以与正则表达式匹配,尽管回文的语言不是规则的。但这似乎是一个坏例子:)