물음표 살인마의 개발블로그

알고리즘 문제/Leetcode

917. Reverse Only Letters

BEstyle 2022. 12. 29. 00:55

Given a string s, reverse the string according to the following rules:

  • All the characters that are not English letters remain in the same position.
  • All the English letters (lowercase or uppercase) should be reversed.

Return s after reversing it.

 

Example 1:

Input: s = "ab-cd"
Output: "dc-ba"

Example 2:

Input: s = "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:

Input: s = "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

 

Constraints:

  • 1 <= s.length <= 100
  • s consists of characters with ASCII values in the range [33, 122].
  • s does not contain '\"' or '\\'.

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

'알고리즘 문제 > Leetcode' 카테고리의 다른 글

1874. Minimize Product Sum of Two Arrays  (0) 2022.12.30
21. Merge Two Sorted Lists  (0) 2022.12.29
206. Reverse Linked List  (0) 2022.12.28
74. Search a 2D Matrix  (0) 2022.12.28
367. Valid Perfect Square  (0) 2022.12.28