Search code examples
javapalindrome

Find palindromes from multiple lines in file


I'd like to ask about finding palindromes (sentence - build a palindromic phrase from a collection of word) from multiple lines in file.

As example the structure of file is as below

Too
text
hot
text
to
text
hoot

Output should be Too hot to hoot, but I have no idea how to implement it this way.

I've created simple function to find single palindromes and will be glad if you could help me improving it

public static boolean findPalindrome(String s) {
int low, high;
low = 0;
high = s.length() - 1;
while (low < high) {
    if (s.charAt(low) != s.charAt(high)) {
        return false;
    }
    low++;
    high--;
}
return true;

I load words from file using nextLine() method

Thank you in advance


Solution

  • I can tell you how to reverse the String to determine if it is a palindrome. I don't know how to effectively build a palindromic phrase based on your requirements. To reverse the String, pass the original String to the StringBuilder constructor and use its reverse method to reverse the string:

      String str = "word";
      StringBuilder buff = new StringBuilder(str);
      boolean isPalindrome = str.equalsIgnoreCase(buff.reverse().toString());
    

    If the original string and the reversed string are equals, then the word is a palindrome. You will have to figure out how to build the phrase.

    To "brute force it", you would have to grab one word and look for all words in the file that ends with the same letter than your keyword starts with. Then, you will have grab the second letter and eliminate words from the list that do not have a matching letter in the new position. Then you have to figure out how get more words, etc. I am not sure how to proceed. But basically, you will have to grab a word and then do a character-by-character comparison with other words in the file, until you consume ALL the words in the file. If the words are in order, it might not be too bad. But, if the words are out of order, you go will have to go rearrange the words and try again.