LeetCode - Algorithms - 125. Valid Palindrome

Problem

125. Valid Palindrome

Java

Two pointers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public boolean isPalindrome(String s) {
final int N = s.length();
char c1, c2;
for (int i = 0, j = N - 1; i < j; ) {
c1 = s.charAt(i);
c2 = s.charAt(j);
if (!Character.isLetterOrDigit(c1))
i++;
else if (!Character.isLetterOrDigit(c2))
j--;
else if (Character.toLowerCase(c1) != Character.toLowerCase(c2)) {
return false;
} else {
i++;
j--;
}
}
return true;
}
}

Submission Detail

  • 481 / 481 test cases passed.
  • Runtime: 2 ms, faster than 98.05% of Java online submissions for Valid Palindrome.
  • Memory Usage: 39 MB, less than 5.64% of Java online submissions for Valid Palindrome.

alphanumeric and binary

1
2
3
4
5
6
7
8
9
10
class Solution {
public boolean isPalindrome(String s) {
s = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
int N = s.length();
for (int i = 0; i < N / 2; i++)
if (s.charAt(i) != s.charAt(N - 1 - i))
return false;
return true;
}
}

Submission Detail

  • 480 / 480 test cases passed.
  • Runtime: 883 ms, faster than 12.58% of Java online submissions for Valid Palindrome.
  • Memory Usage: 47.3 MB, less than 18.43% of Java online submissions for Valid Palindrome.

JavaScript

Algorithms, 4th Edition

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function(s) {
let str = s.toLowerCase().replace(/[^a-zA-Z0-9]/g, "");
const N = str.length;
for (let i = 0; i < N / 2; i++) {
if (str.charAt(i) != str.charAt(N - 1 - i))
return false;
}
return true;
};

Submission Detail

  • 480 / 480 test cases passed.
  • Runtime: 67 ms, faster than 96.43% of JavaScript online submissions for Valid Palindrome.
  • Memory Usage: 44.2 MB, less than 82.85% of JavaScript online submissions for Valid Palindrome.

Two pointers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function(s) {
const N = s.length;
const ALPHANUMERIC = /^[a-z0-9]+$/i;
let c1, c2;
for (let i = 0, j = N - 1; i < j; ) {
c1 = s.charAt(i);
c2 = s.charAt(j);
if (!ALPHANUMERIC.test(c1))
i++;
else if (!ALPHANUMERIC.test(c2))
j--;
else if (c1.toLowerCase() != c2.toLowerCase()) {
return false;
} else {
i++;
j--;
}
}
return true;
};

Submission Detail

  • 480 / 480 test cases passed.
  • Runtime: 102 ms, faster than 45.96% of JavaScript online submissions for Valid Palindrome.
  • Memory Usage: 44.9 MB, less than 61.23% of JavaScript online submissions for Valid Palindrome.