-2

I have a problem for my task. I must make a program that the input is a palindrome / not a palindrome, and the output is return the substring of the string that can be a palindrome in recursive. Example :

"marah" , the output should be, ("m","a","r","a","h") , ("m","ara","h") . I dont know to implement this in recursive. Please anyone who can help me, i'm very need that code. I worked it in java. Thank you, i hope there is a help coming :D .

public static String palindrome(String s) {
    String s, sub;
    int i, c, length;
    Scanner in = new Scanner(System.in);
    System.out.println("Enter a string to print it's all substrings");
    s = in.nextLine();
    length = string.length();
    System.out.println("Substrings of \"" + string + "\" are :-");
    for (c = 0; c < length; c++) {
      for (i = 1; i <= length - c; i++) {
        sub = string.substring(c, c + i);
        System.out.println(sub);
      }
    }
  }
Andy Turner
  • 137,514
  • 11
  • 162
  • 243

2 Answers2

0
public static String longestPalindrome(String s) {
    if (s.isEmpty()) {
        return null;
    }

    if (s.length() == 1) {
        return s;
    }

    String longest = s.substring(0, 1);
    for (int i = 0; i < s.length(); i++) {
        // get longest palindrome with center of i
        String tmp = helper(s, i, i);
        if (tmp.length() > longest.length()) {
            longest = tmp;
        }

        // get longest palindrome with center of i, i+1
        tmp = helper(s, i, i + 1);
        if (tmp.length() > longest.length()) {
            longest = tmp;
        }
    }

    return longest;
}

// Given a center, either one letter or two letter, 
// Find longest palindrome
public static String helper(String s, int begin, int end) {
    while (begin >= 0 && end <= s.length() - 1 && s.charAt(begin) == s.charAt(end)) {
        begin--;
        end++;
    }
    return s.substring(begin + 1, end);
}

if the input is "mama", the output is only "ama", the expected is, "m","a","m","a" , "mam","a" , and "m","ama" . Anybody can help?

0

This is called palindrom partition, you can find it here http://www.programcreek.com/2013/03/leetcode-palindrome-partitioning-java/