File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ // https://leetcode.com/problems/valid-palindrome/
2
+
3
+ class Solution {
4
+ public boolean isPalindrome (String s ) {
5
+
6
+ /*
7
+ * Time Complexity: O(n) where n = length of string. While-loop is iterating
8
+ * string until the halfway point is reached. Keep in mind, in time and space complexity
9
+ * coefficients are dropped. So, O(n) equals to O(n/2).
10
+ *
11
+ * Space Complexity: O(1) because no additional, dynamic data structure
12
+ * was created.
13
+ */
14
+
15
+ // Remove all non-alphanumeric characters and them uncapitalize all letters
16
+ s = s .replaceAll ("[^a-zA-Z0-9]" , "" ).toLowerCase ();
17
+
18
+ // If s has 1 or less characters, then it's automatically a palindrone
19
+ if (s .length () <= 1 ) {
20
+ return true ;
21
+ }
22
+
23
+ // Create a left and right pointer
24
+ int leftPtr = 0 ;
25
+ int rightPtr = s .length () - 1 ;
26
+
27
+ // Iterate string
28
+ while (leftPtr <= rightPtr ) {
29
+
30
+ // If both characters don't equal each other, return false.
31
+ // This string isn't a palindrone
32
+ if (s .charAt (leftPtr ) != s .charAt (rightPtr )) {
33
+ return false ;
34
+ }
35
+
36
+ // Move both pointers closer to the middle of the string
37
+ leftPtr += 1 ;
38
+ rightPtr -= 1 ;
39
+ }
40
+
41
+ // If function is still continuing, return true.
42
+ // This string is a palindrone.
43
+ return true ;
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments