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:

  1. Input: "ab-cd"
  2. Output: "dc-ba"
  1. Input: "a-bC-dEf-ghIj"
  2. Output: "j-Ih-gfE-dCba"

Solution:

  1. /**
  2. * @param {string} S
  3. * @return {string}
  4. */
  5. var reverseOnlyLetters = function(S) {
  6. const arr = S.split('');
  7. const len = arr.length;
  8. const regx = /[A-Za-z]+/;
  9. let left = 0;
  10. let right = len-1;
  11. let temp;
  12. while (left <= right) {
  13. if (!regx.test(arr[left])) {
  14. left ++;
  15. continue;
  16. }
  17. if (!regx.test(arr[right])) {
  18. right --;
  19. continue;
  20. }
  21. temp = arr[left];
  22. arr[left] = arr[right];
  23. arr[right] = temp;
  24. left ++;
  25. right --;
  26. }
  27. return arr.join('');
  28. };

Runtime: 72 ms, faster than 14.75% of JavaScript online submissions for Reverse Only Letters.