- 19
- Posts
- 13
- Years
- Seen Oct 25, 2012
Basically, I want a method to check if a given string sequence is a palindrome or not, however disregarding the existence of whiespaces, commas, and apostrophes. Also, we cannot find the reverse of a string then compare it to the original; the method we are using is checking/comparing the first and last character then incrementing/decrementing and again comparing.
The method I came up with is:
Logically, this seems okay, but a string such as "Madam, I'm Adam" is not working. Technically, it is not a true palindrome, but again I was the program to disregard spaces, commas, and apostrophes. The assignment is due for tomorrow, and this is the only problem I have yet. I tried asking programming forums, but they all were misleading/complicated to fathom considering I am still an amateur in java.
Any help is appreciated, if any.
*please move to its suitable subforum if not right here.
The method I came up with is:
Code:
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;
}
Any help is appreciated, if any.
*please move to its suitable subforum if not right here.