Write a method isPalindromePhrase that accepts a string as argument and returns true or false
indicating if the string is a palindrome or not. In this version of the method, whitespaces, commas, and
apostrophes are ignored. For example, “Lonely Tylenol” and “Madam, I’m Adam” are both palindromes.
The signature of the method should be:
public static boolean isPalindromePhrase(String str)
Again here, you are not allowed to generate a new string in your implementation of this method.
Use this method to write a program Palindromes2 that takes an integer command line argument N
followed by N strings and prints the strings that are palindromes according to this extended definition.
My attempt at a solution:
public class Palindrome
{
public static void main(String[] args)
{
int f = Integer.parseInt(args[0]); // parse integer N
boolean result;
String str = "";
for (int i = 1; i <= f; i++)
{
str = args[i];
result = isPalindromePhrase(str);
if (result) // if value returned is true (IS palindrome)
System.out.println(str + " is a palindrome.");
else
System.out.println(str + " is not a palindrome.");
}
}
public static boolean isPalindromePhrase(String str)
{
if (str.length() <= 1) // a one-character string is always a palindrome
return true;
char rightChars, leftChars;
int first = 0;
int last = str.length() - 1;
while (first < last)
{
leftChars = str.charAt(first); // characters from the left (moving from left to right)
leftChars = Character.toLowerCase(leftChars);
rightChars = str.charAt(last); // characters from the left (moving from right to left)
rightChars = Character.toLowerCase(rightChars);
if (leftChars == ' ' || leftChars == '\'' || leftChars == ',')
{
leftChars = str.charAt(first++);
}
if (rightChars == ' ' || rightChars == '\'' || rightChars == ',')
{
rightChars = str.charAt(last--);
}
if (leftChars == rightChars)
{
first++;
last--;
}
else
return false;
}
return true;
}
}
I tried so many other ways but nothing is working. Can anyone solve this? I have the assignment due for tomorrow and this is the only one that I need to solve.


Sign In
Create Account

Back to top









