日期:2014-05-20  浏览次数:20661 次

新人请教!怎样实现数组中的“回文”判断?
我最近刚开始学java,用的是SavitchIn的《java语言计算机科学与程序设计》看到数组这一章的时候,有道练习题要求进行“回文”判断,很是迷茫!题目是这样的:
       
     
      “回文”指反正读都一样的字符串,比如“warts   n   straw”或“radar”.编写一个程序,该程序接受一串以句号为终结的字符,然后判定这个字符串(不包括句号)是否是回文符串。大家可以假定输入中仅含有字母及空白符号;另外还可以假定输入文字最多长达80个字符。判定输入字符串是否是回文的时候,忽略空格,另外还以为相同字母的大、小写形式是一样的,因此程序认为下面的这行输入也是回文;
“Able   was   I   ere   I   saw   Elba”
程序无须检查字符串是否是正确的英语句子(或单词),它也把字符串“xyzczyx”看作回文。程序中要有一个循环允许用户查证额外的字符串,直到用户要求程序终止为止。这个练习中,应该定义一个名为palindrome的静态方法,方法头如下:
/**
Precondition;The   array   a   contains   letters   and   blanks   in   position   a[0]   through   a[used-1].
Return   true   if   the   string   is   a   palindrome   and   false   otherwise.
*/
public   static   boolean   palindrome(char[]   a,int   used)
程序应该把输入字符串读取至一个基本类型为char的数组中,然后利用该数组及另一个int变量调用上面的方法。后面这个int变量跟踪使用了多少数组。

书上用的输入类是随书附带的SavitchIn类。

------解决方案--------------------
将整个字符串转成字符数组,然后循环比较

public class test{
public static void main(String [] args)
{
String str= "abcde f edcba ";
char[] s=str.toCharArray();
int n=str.length();
boolean flag=true;
for (int i = 0; i <n/2; i++)
{
//System.out.println(s[i]);
//System.out.println(s[n-1-i]);
if(s[i]!=s[n-1-i])
{
flag=false;
break;
}
}
if(flag==true)
{
System.out.println( "是回文 ");
}
else
{
System.out.println( "不是回文 ");
}
}
}
------解决方案--------------------
import java.io.*;
public class ex01
{
public static void main(String args[])
{
try
{
// 缓冲获取系统标准输入
BufferedReader bin = new BufferedReader(new InputStreamReader(System.in));
System.out.println( "请输入: ");
String str = bin.readLine();

while(true)
{

while(str == " " || str.length() == 0 || str == null)
{
System.out.println( "请输入: ");
str = bin.readLine();
}
str = str.trim();
str = str.replaceAll( " ", " ");
System.out.println(str);
if(str.equals( "exit ")) // 输入exit退出程序
{
System.exit(0);
bin.close();
}

char a[] = str.toCharArray();
if(palindrome(a,a.length))
System.out.println( " " +str+ "是回文! ");
else
System.out.println( " "+str+ "不是回文! ");

str= " ";
}
}catch(Exception e){}

}

static boolean palindrome(char a[],int s)
{

for(int i =0,j=s-1;i <s/2;i++,j--)
{
if(a[i] != a[j])
return false;
}

return true;
}
}


哈哈,楼上不说,真没想起来,加上了
------解决方案--------------------
import java.io.*;
public class ex01
{
public static void main(String args[])
{
try
{
// 缓冲获取系统标准输入
BufferedReader bin = new BufferedReader(new InputStreamReader(System.in));
System.out.println( "请输入: ");
String str = bin.readLine();