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
'Leetcode' 카테고리의 다른 글
[LeetCode] Intersection of Two Arrays II 파이썬 (defaultdict, Counter, extend) (0) | 2021.04.13 |
---|---|
[LeetCode] Intersection of Two Arrays 파이썬 (set, intersection) (0) | 2021.04.13 |
[LeetCode] Reverse String 파이썬 (in-place, list.reverse()) (0) | 2021.04.12 |
[LeetCode] Word Pattern 파이썬 (isomorphic, contract mapping) (0) | 2021.04.12 |
[LeetCode] Move Zeros 파이썬 (in-place) (0) | 2021.04.12 |
댓글