Skip to content

Commit 2202a60

Browse files
Update 0125-valid-palindrome.js
Added a new 2 pointer implementation that doesn't use RegEx (only primitives), and no copying of strings.
1 parent cdfcdd9 commit 2202a60

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Diff for: javascript/0125-valid-palindrome.js

+28
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,31 @@ var isPalindrome = function(s) {
5555
}
5656
return true;
5757
};
58+
59+
/**
60+
* 2 Pointer | Midde Convergence | No RegEx | No Copying
61+
* Time O(N) | Space O(1)
62+
* https://leetcode.com/problems/valid-palindrome/
63+
* @param {string} s
64+
* @return {boolean}
65+
*/
66+
var isPalindrome = function (s) {
67+
const isAlpha = c => (c.toLowerCase() >= 'a' && c.toLowerCase() <= 'z') || c >= '0' && c <= '9'
68+
69+
let i = 0;
70+
let j = s.length - 1;
71+
72+
while (i < j) {
73+
if (!isAlpha(s.charAt(i))) {
74+
i++
75+
} else if (!isAlpha(s.charAt(j))) {
76+
j--
77+
} else if (s.charAt(i).toLowerCase() !== s.charAt(j).toLowerCase()) {
78+
return false
79+
} else {
80+
i++
81+
j--
82+
}
83+
}
84+
return true
85+
};

0 commit comments

Comments
 (0)