python-algorithm
leetcode 917. Reverse Only Letters
무적김두칠
2024. 1. 13. 22:45
https://leetcode.com/problems/reverse-only-letters/description/
Reverse Only Letters - LeetCode
Can you solve this real interview question? Reverse Only Letters - 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
leetcode.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class Solution:
def reverseOnlyLetters(self, s: str) -> str:
s = list(s)
left, right = 0, len(s) - 1
while left <= right:
if s[left].isalpha() and s[right].isalpha():
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
elif not s[left].isalpha():
left += 1
elif not s[right].isalpha():
right -= 1
return(''.join(s))
|
cs |
투포인터 개념으로 양끝 에서부터 체크하면됩니당
반응형