Palindrome程序不考虑空格,标点符号和大写/小写

时间:2011-10-12 02:44:52

标签: java palindrome

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

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

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();
  }

} }

2 个答案:

答案 0 :(得分:0)

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

它目前在用户输入的原始字符串上执行此操作。要在内部while - 循环之前更改此设置,请对变量str进行一些过滤。我将留给您确切了解过滤器的内容和方法,但请查看String类中的一些有用方法,例如indexOf()replace()和{{1 }}

答案 1 :(得分: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;