https://leetcode.com/problems/reverse-string/
var reverseString = function(s) {
for (let i = 0; i <= (s.length - 1)/2; i++) {
let temp = s[i];
s[i] = s[s.length - 1 - i];
s[s.length - 1 - i] = temp;
}
return s;
};
we can also use ES6 destructuring assignment
var reverseString = function(s) {
for (let i = 0; i <= (s.length - 1)/2; i++) {
[s[i], s[s.length - 1 - i]] = [s[s.length - 1 - i], s[i]]
}
return s;
};
refactor for
circulation
var reverseString = function(s) {
let i = 0, j = s.length - 1 - i;
while (i <= j) {
[s[i], s[j]] = [s[j], s[i]];
i++;
j--;
}
return s;
};
refactor for
circulation with ES6 destruction
var reverseString = function(s) {
for (let [i, j] = [0, s.length - 1]; i < j; i++, j--) {
[s[i], s[j]] = [s[j], s[i]]
}
return s;
};
with recursion
var reverseString = function(s) {
reverse(0, s.length - 1);
function reverse(i, j) {
if (i >= j) return;
[s[i], s[j]] = [s[j], s[i]];
reverse(++i, --j);
}
return s;
};
I invoke
reverse
with the parametersi++
andj++
first which will led to Maxnum call stack size exceeded
the reason is that the two parameters didn't increased after the first execute