Epic - Palindromes

Print all palindromes of size greater than or equal to 3 of a given string.

动态规划: p[j] 表示对于(i-1..j)这一段的字符串是否为回文。

所以要使p[j] 为1的条件是中间的字符串(i-1..j-1)为回文(p[j-1]==1)且外围的两个值相同(s[i]==s[j]),或者外围两值相同且中间不存在字符串。

def palindromes(s)

    ans, p = [], [0]*s.length

    (s.length-1).downto(0) do |i|

        (s.length-1).downto(i) do |j|

            if s[i] == s[j] and (j-i <= 1 or p[j-1] == 1)

                p[j] = 1

                ans << s[i..j] if j-i > 1

            else

                p[j] = 0

            end

        end

    end

    ans

end

 

你可能感兴趣的:(ROM)