0

我正在尝试创建一个回文程序,该程序在确定字符串是否为回文时不考虑空格、标点符号以及大小写。

如何更改此代码以执行我之前所说的操作?

package palindrome;

import java.util.Scanner;

public class Palindrome {

   public static void main (String[] args)
 {
  String str, another = "y";
  int left, right;
  Scanner scan = new Scanner (System.in);

  while (another.equalsIgnoreCase("y")) // allows y or Y
  {
     System.out.println ("Enter a potential palindrome:");
     str = scan.nextLine();



     left = 0;
     right = str.length() - 1;

     while (str.charAt(left) == str.charAt(right) && left < right)
     {
        left++;
        right--;
     }

     System.out.println();

     if (left < right)
        System.out.println ("That string is NOT a palindrome.");
     else
        System.out.println ("That string IS a palindrome.");

     System.out.println();
     System.out.print ("Test another palindrome (y/n)? ");
     another = scan.nextLine();
  }

} }

4

2 回答 2

0

您当前的代码查看变量str并检查字符是否从左到右和从右到左读取相同(毕竟,回文是什么)。

它目前在用户输入的原始字符串上执行此操作。要更改它,在您的内部while循环之前,对您的变量进行一些过滤str。我将留给您弄清楚究竟要过滤什么/如何过滤,但请看一下String类中的一些有用方法,indexOf()例如replace()substring()

于 2011-10-12T03:14:49.750 回答
0
The heart of your program is in following loop

while (str.charAt(left) == str.charAt(right) && left < right)
    {
        left++;
        right--;
    }


what you are doing here is to compare the characters without honoring the condition of ignoring space and punctuation here. Your logic should be such that while picking the characters for comparison (either from left or right) you will need to skip that character and move for the next character.
To make picture clearer see the following :

Input string :
inStr = Ma'lyalam

Step 1:
Since you have to ignore the case do following
inStr = inStr.toLowerCase();

Step 2:

 1. int left =0 , right = 8
 2. char chLeft, chRight
 3. chLeft = m , chRight = m 
 4. chLeft == chRight -> true, increment left and decrement right
 5. chLeft = a , chRight = a
 6. chLeft == chRight -> true, increment left and decrement right
 7. chLeft = ' , chRight = l -> Since chLeft = ' skip it, increment left so chLeft = l. Now continue like above

so the code should look like

    boolean isPlaindrome = false;
    str = str.toLowerCase();
    char chLeft, chRight;
    while (left < right)
    {
    chLeft = str.charAt(left);
    chRight = str.charAt(right)
    if (chLeft == ''' || chLeft == ' ')
     {
       left++
       continue;
     }
     else if (chRight == ''' || chRight == ' ')
     {
       right--;
       continue;
     }

     if (chLeft == chRight)
    {
     left++; right--;
    }
    else
    {
    break;
    }
    }

    if (left == right)
     isPlaindrome = true;
于 2011-10-12T03:17:31.333 回答