我的任务有问题。我必须创建一个程序,输入是回文/不是回文,输出返回字符串的子串,可以是递归的回文。示例:
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);
}
}
}
答案 0 :(得分: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);
}
如果输入是&#34; mama&#34;,输出只是&#34; ama&#34;,预期是,&#34; m&#34;&#34; a&#34; &#34; M&#34;&#34;&#34; ,&#34; mam&#34;,&#34; a&#34; ,&#34; m&#34;,&#34; ama&#34; 。有人可以帮忙吗?
答案 1 :(得分:0)
这称为palindrom分区,您可以在http://www.programcreek.com/2013/03/leetcode-palindrome-partitioning-java/
找到它