Skip to content

Latest commit

 

History

History
32 lines (29 loc) · 515 Bytes

917.reverse-only-letters.md

File metadata and controls

32 lines (29 loc) · 515 Bytes
/**
 * @param {string} S
 * @return {string}
 */
var reverseOnlyLetters = function (S) {
  let A = S.split("");

  function isChar(c) {
    return ("a" <= c && c <= "z") || ("A" <= c && c <= "Z");
  }

  function swap(i, j) {
    let t = A[i];
    A[i] = A[j];
    A[j] = t;
  }

  for (let i = 0, j = A.length - 1; i < j; ) {
    while (!isChar(A[i]) && i < j) {
      i++;
    }
    while (!isChar(A[j]) && i < j) {
      j--;
    }
    swap(i, j);
    i++;
    j--;
  }
  return A.join("");
};