컴퓨터공학/알고리즘 문제 풀이

[GeeksforGeeks] Special array reversal

TaeGyeong Lee 2023. 2. 22. 22:00

 

Special array reversal | Practice | GeeksforGeeks

Given a string S, containing special characters and all the alphabets, reverse the string without affecting the positions of the special characters. Example 1: Input: S = "A&B" Output: "B&A" Explanation: As we i

practice.geeksforgeeks.org

접근

  • Two pointer 를 활용해 문자 비교 및 변경
  • isalphabet() 함수를 활용
  • Python 문자열 내 두 문자를 스왑하는 함수가 따로 제공되지 않는다는 점 참고

솔루션

class Solution:
    def reverse(self, s):
        # code here
        pivot_left = 0
        pivot_right = len(s)-1
        
        while pivot_left < pivot_right:
            if s[pivot_left].isalpha() and \
                s[pivot_right].isalpha():
                    c_from_left, c_from_right = s[pivot_left], s[pivot_right]
                    s = s[:pivot_left] + c_from_right + s[pivot_left+1:pivot_right] + c_from_left + s[pivot_right+1:]
                    pivot_left += 1
                    pivot_right -= 1
            if s[pivot_left].isalpha() == False:
                pivot_left += 1
            if s[pivot_right].isalpha() == False:
                pivot_right -= 1
        return s