我正在编写一些代码来查找字符串中最长的回文。我想从索引0开始,然后将子字符串的增加长度推送到数组:
ex:
string = "ababa"
[["a", "b"], ["a", "b", "a"], ["a", "b", "a", "b"], ["a", "b", "a", "b", "a"]]
然后它应该从索引1开始并执行相同的操作:
ex:
string = "ababa"
[["b","a"],["b","a","b"],["b","a","b","a"]
这应该一直持续到索引的长度为-1。但是,以下代码在经历了从第一个索引开始的所有迭代后停止并且只返回:
[["a", "b"], ["a", "b", "a"], ["a", "b", "a", "b"], ["a", "b", "a", "b", "a"]]
我逻辑中的缺陷是什么?代码
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
答案 0 :(得分:0)
我相信这就是你所追求的:
def longest_palindrome(s)
arr = s.chars
output = []
(0...s.length).each do |start|
(start + 1...s.length).each do |place|
output << arr[start..place]
end
end
output
end
longest_palindrome("ababa")
=> [["a", "b"], ["a", "b", "a"], ["a", "b", "a", "b"], ["a", "b", "a", "b", "a"], ["b", "a"], ["b", "a", "b"], ["b", "a", "b", "a"], ["a", "b"], ["a", "b", "a"], ["b", "a"]]
使用迭代器确实简化了事情。这是一个更简洁的版本:
def longest_palindrome(s)
output = (0...s.length).flat_map do |start|
(start + 1...s.length).map do |place|
s[start..place]
end
end
end
longest_palindrome("ababa")
=> ["ab", "aba", "abab", "ababa", "ba", "bab", "baba", "ab", "aba", "ba"]
答案 1 :(得分:0)
工作,非优化,即时写入30分钟,谁知道最慢的最长回文查找器:
def longest_palindrome(string, min_size = 2)
string = string.downcase # we will not be taking
return string if string == string.reverse # skip all calculaions of the passed string itself is a palindrome in original order
letters = string.chars # Convert string to array of bytes
combinations = [] # Initialize all letter combinations
(min_size..letters.size).each do |n| # min_size is the shortest length a palindrome is allowed to be, default 2
combinations.concat(letters.combination(n).to_a) # concat all combinations for n amount of characters in the string
end
palindromes = [] # Initialize array for all palindromes
combinations.each do |combo| # interate every combo
combo.size.times do # for every letter ordering is done via size of this letter combo
palindromes << combo.dup if combo == combo.reverse # add to list of palindromes if the combinations is the same backwards
combo.rotate! # rotate the letters for next order checking
end
end
palindromes.sort {|a, b| a.size <=> b.size }.last.join # sort the palidromes by length, take the biggest one, and return it as a full string
end
p longest_palindrome("racecar") #=> racecar
p longest_palindrome("applesauce") #=> pecep
p longest_palindrome("madam im adam") #=> mada m adam
p longest_palindrome("madamimadam") #=> madamimadam
但它有效。 正如你所看到的那样,当混合中添加空格/条纹时,是否会变得奇怪。 如果需要,您可以随时在第一行清除它的字符串。
Viva la无算法编码!