[Leetcode]345. Reverse Vowels of a String
2024. 7. 26. 12:32ㆍAlgorithm
1. Problem :
2. Solution 1 :
class Solution:
def reverseVowels(self, s: str) -> str:
vowel_list = ["a","e","i","o","u","A","E","I","O","U"]
string_list = list(s)
left,right = 0,len(string_list)-1
while left < right:
if string_list[left] in vowel_list and string_list[right] in vowel_list:
string_list[left],string_list[right] = string_list[right], string_list[left]
left += 1
right -= 1
elif string_list[left] in vowel_list:
right -= 1
elif string_list[right] in vowel_list:
left += 1
else:
left += 1
right -= 1
return "".join(string_list)
위 solution은 str을 리스트로 만든 다음, left, right (two pointer)를 이용해, 모음이 나오는 순간, 서로 바꿔치기하는 코드다.
그런 다음, return으로 str을 다시 return 한다.
3. solution 2 :
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = set('aeiouAEIOU')
s = list(s)
i, j = 0, len(s) - 1
while i < j:
while i < j and s[i] not in vowels:
i += 1
while i < j and s[j] not in vowels:
j -= 1
if i < j:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
return ''.join(s)
이 solution 같은 경우 첫 번째 solution과 같은 solution이다. 하지만 표현 방식만 다르다. while문안에 while문을 이용해, logic을 작성했다.
'Algorithm' 카테고리의 다른 글
[Leetcode]238. Product of Array Except Self (0) | 2024.07.27 |
---|---|
[Leetcode]151. Reverse Words in a String (0) | 2024.07.26 |
[Leetcode]605. Can Place Flowers (0) | 2024.07.25 |
[Leetcode]1431. Kids With the Greatest Number of Candies (0) | 2024.07.25 |
[Leetcode]894. All Possible Full Binary Trees (0) | 2024.07.25 |