Question:
Given a string S, return the “reversed” string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example:
Input: "ab-cd"Output: "dc-ba"
Input: "a-bC-dEf-ghIj"Output: "j-Ih-gfE-dCba"
Solution:
/*** @param {string} S* @return {string}*/var reverseOnlyLetters = function(S) {const arr = S.split('');const len = arr.length;const regx = /[A-Za-z]+/;let left = 0;let right = len-1;let temp;while (left <= right) {if (!regx.test(arr[left])) {left ++;continue;}if (!regx.test(arr[right])) {right --;continue;}temp = arr[left];arr[left] = arr[right];arr[right] = temp;left ++;right --;}return arr.join('');};
Runtime: 72 ms, faster than 14.75% of JavaScript online submissions for Reverse Only Letters.
