Check if is given String is a Palindrome
There are a couple of ways we can check if the given String is a palindrome or not.
Let's say that the provided String can also contain non-alphanumeric characters.
We need to first remove the non-alphanumeric characters, and then check if it is a plaindrome.
Note: We also need to convert the String to lowercase to compare the chars properly.
We need to first remove the non-alphanumeric characters, and then check if it is a plaindrome.
Note: We also need to convert the String to lowercase to compare the chars properly.
Solution:
public boolean isPalindrome(String str) {
String newStr = "";
// first, remove non-alphanumerical characters
for (int i = 0; i < str.length(); i++) {
if (Character.isLetterOrDigit(str.charAt(i))) {
newStr += str.charAt(i);
}
}
newStr = newStr.toLowerCase();
// now check if it is a palindrome
for (int i = 0, j = newStr.length() - 1; i <= j; i++, j--) {
if (newStr.charAt(i) != newStr.charAt(j)) {
return false;
}
}
return true;
}
Here, we created a new string and put all alphanumeric characters from the input into that one.
Next, we used the two-pointer technique to check for chars equality.
We can replace the newStr with StringBuilder - for efficiency.
We can replace the newStr with StringBuilder - for efficiency.
The above question is a bit more complicated version than the question that asks to just check if the String is palindrome or not. In that case, we do not need to consider lowercase/uppercase, and removing the non-alphanumeric characters is not required.
In that case, here is a solution using a StringBuilder:
public boolean isPalindrome(String str) {
return new StringBuilder(str).reverse().toString().equals(str);
}
}
So we just reverse the string and compare it with the input string.
Or we can use a for loop and a two-pointer approach, just like in the previous example:
Or we can use a for loop and a two-pointer approach, just like in the previous example:
public static boolean isPalindrome(String str) {
for (int i = 0, j = str.length() - 1; i <= j; i++, j--) {
if (str.charAt(i) != str.charAt(j)) {
return false;
}
}
return true;
}
No comments:
Post a Comment