Программа Palindrome, которая не учитывает пробелы, знаки препинания и прописные / строчные буквы - PullRequest
0 голосов
/ 12 октября 2011

Я пытаюсь создать программу на палиндроме, которая не учитывает пробелы, знаки препинания, а также прописные и строчные буквы при определении, является ли строка палиндромом.

Как я могу изменить данный код, чтобы сделать то, что я сказал ранее?

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 голосов
/ 12 октября 2011
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;
0 голосов
/ 12 октября 2011

Ваш текущий код просматривает переменную str и проверяет, одинаковы ли символы для чтения слева направо и справа налево (то есть, в конце концов, что такое палиндром).

В настоящее время он делает это с исходной строкой, введенной пользователем. Чтобы изменить это, перед внутренним while -циклом выполните некоторую фильтрацию для вашей переменной str. Я оставлю это вам, чтобы выяснить, что именно / как фильтровать, но взгляните на некоторые полезные методы класса String , такие как indexOf(), replace() и substring().

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...