Java判断是否回文,忽略标点和空格部分怎么写?
来源:百度知道 编辑:UC知道 时间:2024/05/26 00:14:47
public class Palindrome
{
static private String text;
static private int firstIndex;
static private int lastIndex;
public static boolean isPalindrome(String text, int firstIndex,int lastIndex)
{
text = text.toLowerCase();
firstIndex = 0;
lastIndex = text.length()-1;
for( int i=0; i < text.length(); i++)
{
char letter = text.charAt(i);
if(character.isLetterOrDigit(letter)
这里 我要忽略标点和空格部分,但是怎么继续写下去呢??
}
if (firstIndex >= lastIndex)
return true; // Base Case
else if (text.charAt(firstIndex) != text.charAt(lastIndex))
return false;
else
{
return isPalindrome(text, firstIndex + 1, lastIndex -1);
}
}
}
{
static private String text;
static private int firstIndex;
static private int lastIndex;
public static boolean isPalindrome(String text, int firstIndex,int lastIndex)
{
text = text.toLowerCase();
firstIndex = 0;
lastIndex = text.length()-1;
for( int i=0; i < text.length(); i++)
{
char letter = text.charAt(i);
if(character.isLetterOrDigit(letter)
这里 我要忽略标点和空格部分,但是怎么继续写下去呢??
}
if (firstIndex >= lastIndex)
return true; // Base Case
else if (text.charAt(firstIndex) != text.charAt(lastIndex))
return false;
else
{
return isPalindrome(text, firstIndex + 1, lastIndex -1);
}
}
}
忽略标点就要写循环判断了,根据ASCII码判断。
去空格有个方法可以用。replace(要去空格的变量," ","");记不太清了,应该是这样。是把要去空格变量里的“ ”空格替换为“”什么都没有。
在循环上面定义一个String text2 = "";
循环里面写:
text2 = text2 + letter;
循环完以后,test2就是去掉空格和标点的字符串了。