Reverse Only Letters
Description
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" Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba"
Example 3:
Input: "Test1ng-Leet=code-Q!" Output: "Qedo1ct-eeLg=ntse-T!"
Note:
- S.length <= 100
- 33 <= S[i].ASCIIcode <= 122
- Sdoesn't contain- \or- "
Solution(javascript)
/*
 * @lc app=leetcode id=917 lang=javascript
 *
 * [917] Reverse Only Letters
 */
// @lc code=start
/**
 * @param {string} S
 * @return {string}
 */
const reverseOnlyLetters = function (S) {
  const arr = S.split('')
  let left = 0
  let right = arr.length - 1
  const swap = (a, b) => {
    const temp = arr[a]
    arr[a] = arr[b]
    arr[b] = temp
  }
  const isLetter = (x = '') => /[a-zA-Z]/.test(x)
  while (left <= right) {
    while (!isLetter(arr[left])) {
      left += 1
      if (left > right) {
        break
      }
    }
    while (!isLetter(arr[right])) {
      right -= 1
      if (left > right) {
        break
      }
    }
    if (left > right) {
      break
    }
    swap(left, right)
    left += 1
    right -= 1
  }
  return arr.join('')
}
// @lc code=end