Reverse Only Letters in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string S, we have to find the reversed string where all characters that are not a letter will not change their positions and all letters reverse their positions. So if the given string is "a-bC-dEf-ghIj", then output will be "j-Ih-gfE-dCba"

To solve this, we will follow these steps −

  • We will use the regular expression library to solve this
  • if S is empty, then return S
  • str := an empty string, index1 := 0 and index2 := length of S – 1
  • while index1 < length of S
    • if index2 >= 0 and S[index1] is alphabet and S[index2] is alphabet
      • str := str + S[index2]
      • decrease index2 by 1, and increase index1 by 1
    • else if S[index1] is alphabet then decrease index2 by 1
    • else if S[index1] is not alphabet, then str := str + S[index1], increase index1 by 1
    • else decrease index2 by 1, and increase index1 by 1
  • return str

Example

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
   def reverseOnlyLetters(self, S):
      if not S:
         return S
      str_= ""
      index1 = 0
      index2 = len(S)-1
      while index1<len(S):
         #print(index1,index2)
         if index2>=0 and S[index1].isalpha() and S[index2].isalpha():
            str_+=S[index2]
            index2 -= 1
            index1 += 1
         elif S[index1].isalpha():
            index2-=1
         elif not S[index1].isalpha():
            str_+=S[index1]
            index1+=1
         else:
            index2 -= 1
            index1 += 1
      return str_
ob1 = Solution()
print(ob1.reverseOnlyLetters("a-bC-dEf-ghIj"))

Input

"a-bC-dEf-ghIj"

Output

"j-Ih-gfE-dCba"
raja
Published on 16-Jan-2020 16:04:34
Advertisements