[Leet Code] Reverse Only Letters

Matthew Boyd
2 min readFeb 18, 2021

--

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

Problem:

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:

  1. S.length <= 100
  2. 33 <= S[i].ASCIIcode <= 122
  3. S doesn't contain \ or "

Solution:

class Solution(object):
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
left = 0
right = len(S) -1
S = list(S)
while left < right:
if str(S[left]).isalpha() and str(S[right]).isalpha():
temp = S[left]
S[left] = S[right]
S[right] = temp
left += 1
right -= 1
elif not str(S[left]).isalpha():
left += 1
else:
right -=1

return "".join(S)

Explanation:

For this problem, we can use a two pointer array approach. We made the string into an array / list. Then we want to set our indexes on the left (0) and right (len-1). Then we do a while look to make sure that left is less than right, then we check that each character at their respective indexes (left and right) are alphabetical. This will make sure other characters are dismissed, if they are, then we switch their positions. If one of them isn’t, then we increment this value or decrement. Incrementing the left side if it is not alphabetical, and decrementing the right side if it is not alphabetical. Therefore going through the entire array.

--

--

Matthew Boyd
Matthew Boyd

Written by Matthew Boyd

Learning, and posting my findings!

No responses yet