mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-10 13:39:08 +08:00
ignore non-alphanumeric
This commit is contained in:
@ -22,4 +22,29 @@ class Palindrome {
|
||||
|
||||
return SecondWay(x.substring(1, x.length() - 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* This method ignores all non-alphanumeric characters and case runs in O(n)
|
||||
* where n is the length of s
|
||||
*
|
||||
* @param s String to check
|
||||
* @return true if s is palindrome else false
|
||||
*/
|
||||
public boolean isPalindrome(String s) {
|
||||
s = s.toLowerCase().trim();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (char c : s.toCharArray()) {
|
||||
if (Character.isLetter(c) || Character.isDigit(c))
|
||||
sb.append(c);
|
||||
}
|
||||
s = sb.toString();
|
||||
int start = 0;
|
||||
int end = s.length() - 1;
|
||||
while (start <= end) {
|
||||
if (s.charAt(start++) != s.charAt(end--))
|
||||
return false;
|
||||
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user