Leetcode 953 Solution

This article provides solution to leetcode question 953 (reverse-only-letters)

https://leetcode.com/problems/reverse-only-letters

Solution

class Solution:
    def reverseOnlyLetters(self, S: str) -> str:
        letters = [c for c in S if c.isalpha()]
        ans = []
        for ch in S:
            if ch.isalpha():
                ans.append(letters.pop())
            else:
                ans.append(ch)
        return "".join(ans)