我一直在尝试解决寻找字符串最长回文的问题。虽然我可以通过中间元素来做到这一点,但我想通过 string.reverse 尝试它:
这是我的代码:
怀疑:我正在使用 string.reverse 来查找给定字符串的反向,然后尝试比较反向字符串和输入字符串中的每个子字符串,但这不会给我最大的回文,但它会给出所有可能的回文.. . 另外我在某处犯了一些错误,请帮助我找到那个......
public class StringPalindrome {
public static void main(String args[]) {
StringBuilder strBuilder = new StringBuilder("Shubham");
StringBuilder a = new StringBuilder("");
a = strBuilder.reverse(); //Reverse the string and saving it into other string
for(int i=0;i<strBuilder.length();i++){ // Loop one for begin index
for(int j=1;i<strBuilder.length() + 1;j++){ // Loop two for end index
if(a.substring(i, j).equals(strBuilder.substring(i, j))){ // comparing
System.out.println(strBuilder.substring(i, j)); //printing palindrome
}
}
}
}
我无法想到如何找到最长的回文?
我认为通过使用 string.reverse,它将是一个短代码:
虽然我可以这样做:
public class LongestPalindrome
{
static public String expand(String string, int a, int b)
{
if (a > b)
return null;
int left = a, right = b;
while (left >= 0 && right < string.length() && string.charAt(left) == string.charAt(right))
{
left--;
right++;
}
return string.substring(left + 1, right);
}
static public String longestPalindrome(String string)
{
if (string == null)
return null;
String longest = string.substring(0, 1);
for (int i = 0; i < string.length() - 1; i++)
{
String palindrome = expand(string, i, i);
if (palindrome.length() > longest.length())
{
longest = palindrome;
}
palindrome = expand(string, i, i + 1);
if (palindrome.length() > longest.length())
{
longest = palindrome;
}
}
return longest;
}
public static void main(String[] args)
{
System.out.println(longestPalindrome("baraik"));
}
}