File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public boolean isPalindrome (String s ) {
3
+ StringBuilder cleaned = new StringBuilder ();
4
+
5
+ for (char c : s .toCharArray ()) {
6
+ if (Character .isLetterOrDigit (c )) {
7
+ cleaned .append (Character .toLowerCase (c ));
8
+ }
9
+ }
10
+
11
+ int left = 0 ;
12
+ int right = cleaned .length () - 1 ;
13
+ while (left < right ) {
14
+ // Fail fast: return false as soon as a mismatch is found
15
+ if (cleaned .charAt (left ) != cleaned .charAt (right )) {
16
+ return false ;
17
+ }
18
+ left ++;
19
+ right --;
20
+ }
21
+
22
+ return true ;
23
+ }
24
+ }
25
+
26
+ /**
27
+ converting all uppercase letters into lowercase letters
28
+ removing all non-alphanumeric char
29
+
30
+ 1. cleaning
31
+ 0. str -> char with for-each loop
32
+ 1. check char if isLetterOrDigit
33
+ 2. make char to LowerCase
34
+ * Character Class static method
35
+ 2. two ptrs comparison while left < right
36
+ s[i] == s[n - 1 - i]
37
+
38
+ - Time: O(n)
39
+
40
+ /** REMEMBER
41
+ 1. length vs length()
42
+
43
+ arr.length => field
44
+ String(Builder).length() => method
45
+
46
+ 2. “fail fast” approach:
47
+ As soon as we detect something wrong, we exit early.
48
+ */
You can’t perform that action at this time.
0 commit comments