'JavaScript syntactic sugar when incrementing/decrementing variable
LeetCode 680. Valid Palindrome II Easy
Given a string s, return true if the s can be palindrome after deleting at most one character from it.
Can someone tell me why the first code below is much faster than the second code? The only difference between them is how I'm incrementing and decrementing my variables in the isPalindrome function.
var validPalindrome = function (s) {
let left = 0;
let right = s.length - 1;
while (left < right) {
if (s[left] !== s[right]) {
return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1);
}
left++;
right--;
}
return true;
};
let isPalindrome = (s, left, right) => {
while (left < right) {
if (s[left++] !== s[right--]) { // writing it this way is much faster
return false;
}
}
return true;
}
/*
Runtime: 72 ms, faster than 98.87% of JavaScript online submissions for Valid Palindrome II.
Memory Usage: 48.7 MB, less than 21.51% of JavaScript online submissions for Valid Palindrome II.
*/
var validPalindrome = function (s) {
let left = 0;
let right = s.length - 1;
while (left < right) {
if (s[left] !== s[right]) {
return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1);
}
left++;
right--;
}
return true;
};
let isPalindrome = (s, left, right) => {
while (left < right) {
if (s[left] !== s[right]) {
return false;
}
left++; // this is slightly slower
right--;
}
return true;
}
/*
Runtime: 116 ms, faster than 58.84% of JavaScript online submissions for Valid Palindrome II.
Memory Usage: 48.2 MB, less than 27.24% of JavaScript online submissions for Valid Palindrome II.
*/
Example 1:
Input: s = "aba"
Output: true
Example 2:
Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.
Example 3:
Input: s = "abc"
Output: false
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
