https://leetcode.com/problems/reverse-only-letters/description/
/**
* @param {string} s
* @return {string}
*/
var reverseOnlyLetters = function (s) {
if (s.length === 1) {
return s;
}
let result = s.split('');
let leftIndex = 0;
let rightIndex = s.length - 1;
while (leftIndex <= rightIndex) {
const isLeftEngString = isEngString(s[leftIndex]);
const isRightEngString = isEngString(s[rightIndex]);
if (isLeftEngString && isRightEngString) {
result[leftIndex] = s[rightIndex];
result[rightIndex] = s[leftIndex];
leftIndex++;
rightIndex--;
} else {
if (!isLeftEngString) {
leftIndex++;
}
if (!isRightEngString) {
rightIndex--;
}
}
}
return result.join('');
};
const isEngString = (letter) => {
const engLettersRegex = /[a-zA-Z]/;
return engLettersRegex.test(letter);
};
Runtime 59 ms Beats 97.4%
Memory 42.6 MB Beats 30.37%