Reverse Only Letters

easy two pointers string

Problem

Given a string s, reverse the string according to the following rules: all the characters that are not English letters remain in the same position, and all the English letters (lowercase or uppercase) should be reversed. Return s after the reversal.

Inputs = "a-bC-dEf-ghIj"
Output"j-Ih-gfE-dCba"
The hyphens stay put; the letters a,b,C,d,E,f,g,h,I,j are reversed to j,I,h,g,f,E,d,C,b,a.

def reverse_only_letters(s):
    chars = list(s)
    i, j = 0, len(chars) - 1
    while i < j:
        if not chars[i].isalpha():
            i += 1
        elif not chars[j].isalpha():
            j -= 1
        else:
            chars[i], chars[j] = chars[j], chars[i]
            i += 1
            j -= 1
    return "".join(chars)
function reverseOnlyLetters(s) {
  const chars = s.split("");
  let i = 0, j = chars.length - 1;
  const isAlpha = (c) => /[a-zA-Z]/.test(c);
  while (i < j) {
    if (!isAlpha(chars[i])) i++;
    else if (!isAlpha(chars[j])) j--;
    else {
      [chars[i], chars[j]] = [chars[j], chars[i]];
      i++;
      j--;
    }
  }
  return chars.join("");
}
class Solution {
    public String reverseOnlyLetters(String s) {
        char[] chars = s.toCharArray();
        int i = 0, j = chars.length - 1;
        while (i < j) {
            if (!Character.isLetter(chars[i])) i++;
            else if (!Character.isLetter(chars[j])) j--;
            else {
                char t = chars[i];
                chars[i] = chars[j];
                chars[j] = t;
                i++;
                j--;
            }
        }
        return new String(chars);
    }
}
string reverseOnlyLetters(string s) {
    int i = 0, j = (int)s.size() - 1;
    while (i < j) {
        if (!isalpha((unsigned char)s[i])) i++;
        else if (!isalpha((unsigned char)s[j])) j--;
        else {
            swap(s[i], s[j]);
            i++;
            j--;
        }
    }
    return s;
}
Time: O(n) Space: O(n)