Leetcode
[LeetCode] Reverse Vowels of String 파이썬 (swap, two pointer)
YGSEO
2021. 4. 13. 03:20
728x90
reverse string 문제에서 진화된 문제
i, j = 0, len(s) - 1
while i < j:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
2개의 변수(i,j)들을 활용해서 swap
dict나 list 뿐만 아니라 string 도 not in 구문이 가능하다는 점.
i는 forward
j는 backward
탐색 ㄱ
vowel의 위치를 찾을 경우 i,j swap
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
vowels = "aeiou"
string = list(s)
i, j = 0, len(s) - 1
while i < j:
if string[i].lower() not in vowels:
i += 1
elif string[j].lower() not in vowels:
j -= 1
else:
string[i], string[j] = string[j], string[i]
i += 1
j -= 1
return "".join(string)
출처: github.com/jiapengwen/LeetCode/blob/master/Python/reverse-vowels-of-a-string.py
728x90