Recursive Prolog predicate for reverse / palindrome

Ad 1: It is impossible to define reverse/2 as a (directly edit thx to @repeat: tail) recursive predicate – unless you permit an auxiliary predicate. Ad 2: palindrome(X) :- reverse(X,X). But the easiest way is to define such predicates with DCGs: iseq([]) –> []. iseq([E|Es]) –> iseq(Es), [E]. reverse(Xs, Ys) :- phrase(iseq(Xs), Ys). palindrome(Xs) :- … Read more

how to find longest palindromic subsequence?

This can be solved in O(n^2) using dynamic programming. Basically, the problem is about building the longest palindromic subsequence in x[i…j] using the longest subsequence for x[i+1…j], x[i,…j-1] and x[i+1,…,j-1] (if first and last letters are the same). Firstly, the empty string and a single character string is trivially a palindrome. Notice that for a … Read more

A better algorithm to find the next palindrome of a number string

This seems like a lot of code. Have you tried a very naive approach yet? Checking whether something is a palindrome is actually very simple. private boolean isPalindrome(int possiblePalindrome) { String stringRepresentation = String.valueOf(possiblePalindrome); if ( stringRepresentation.equals(stringRepresentation.reverse()) ) { return true; } } Now that might not be the most performant code, but it gives … Read more