관리 메뉴

솜씨좋은장씨

[leetCode] 917. Reverse Only Letters (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 917. Reverse Only Letters (Python)

솜씨좋은장씨 2020. 9. 4. 02:59
728x90
반응형

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:
    def reverseOnlyLetters(self, S: str) -> str:
        temp = []
        indexs = {}
        
        answer = []
        
        cnt = 0
        
        s_list = list(S)
        
        for i in range(len(s_list)):
            if s_list[i].isalpha() == True:
                temp.append(s_list[i])
                cnt = cnt + 1
            if s_list[i].isalpha() == False:
                indexs[i] = s_list[i]
        if cnt == len(S):
            answer = S[::-1]
        else:
            keys = list(indexs.keys())
            temp = temp[::-1]
            
            idx = 0
            
            for i in range(len(S)):
                if i in keys:
                    answer.append(indexs[i])
                elif i not in keys:
                    answer.append(temp[idx])
                    idx = idx + 1
                    
            answer = ''.join(answer)
            
        return answer

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments