126. Letters-Only Reverse

You are given a string s that mixes English letters with other printable characters such as digits, dashes and punctuation. Reverse the order of the letters only: the letters must appear in the opposite order, while every non-letter character stays at the exact position where it was. Letters keep their case.

Return the new string. For example, a string with the letters a, b, c and a dash between b and c becomes a string where the letters read c, b, a and the dash is still in the same slot. Use two pointers that move inwards and swap the letters they stop on.

Example 1

Input:
s = "a1b2c3"
Output:
"c1b2a3"
Explanation:

The letters a, b, c become c, b, a while the digits keep positions 2, 4 and 6: c1b2a3.

Example 2

Input:
s = "Qwe-rty!"
Output:
"ytr-ewQ!"
Explanation:

The letters Q w e r t y read y t r e w Q after reversing, and the dash and the exclamation mark do not move: ytr-ewQ!.

Constraints

1 ≤ s.length ≤ 105

s contains printable ASCII characters except space

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…