Skip to content

Commit a4156fc

Browse files
committed
ignore non-alphanumeric
1 parent 11864ca commit a4156fc

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Others/Palindrome.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,29 @@ public boolean SecondWay(String x) {
2222

2323
return SecondWay(x.substring(1, x.length() - 1));
2424
}
25+
26+
/**
27+
* This method ignores all non-alphanumeric characters and case runs in O(n)
28+
* where n is the length of s
29+
*
30+
* @param s String to check
31+
* @return true if s is palindrome else false
32+
*/
33+
public boolean isPalindrome(String s) {
34+
s = s.toLowerCase().trim();
35+
StringBuilder sb = new StringBuilder();
36+
for (char c : s.toCharArray()) {
37+
if (Character.isLetter(c) || Character.isDigit(c))
38+
sb.append(c);
39+
}
40+
s = sb.toString();
41+
int start = 0;
42+
int end = s.length() - 1;
43+
while (start <= end) {
44+
if (s.charAt(start++) != s.charAt(end--))
45+
return false;
46+
47+
}
48+
return true;
49+
}
2550
}

0 commit comments

Comments
 (0)