DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Reverse Only Letters

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.
All the English letters (lowercase or uppercase) should be reversed.
Return s after reversing it.

Example 1:

Input: s = "ab-cd"
Output: "dc-ba"
Example 2:

Input: s = "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:

Input: s = "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

var reverseOnlyLetters = function (arr) {
  let str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  let start = 0;
  let end = arr.length - 1;
  let s = arr.split("");

  while (start < end) {
    let charStart = s[start];
    let charEnd = s[end];

    if (str.includes(charStart) && str.includes(charEnd)) {
      s = swapChars(s, start, end);
      start++;
      end--;
    }

    if (!str.includes(charStart)) {
      start++;
    }
    if (!str.includes(charEnd)) {
      end--;
    }
  }
  return s.join("");
};

const swapChars = (s, start, end) => {
  let firstChar = s[start];
  let enChar = s[end];
  s[start] = enChar;
  s[end] = firstChar;
  return s;
};

console.log(reverseOnlyLetters("ab-cd"));
// Output: "dc-ba"

console.log(reverseOnlyLetters("a-bC-dEf-ghIj"));
// Output: "j-Ih-gfE-dCba"

console.log(reverseOnlyLetters("Test1ng-Leet=code-Q!"));
// Output: "Qedo1ct-eeLg=ntse-T!"

Enter fullscreen mode Exit fullscreen mode

Top comments (0)