문제

 

https://leetcode.com/problems/reverse-vowels-of-a-string/

 

Reverse Vowels of a String - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.

 

문자열 s안에 있는 모든 모음들을 뒤집어서 반환해라, 모음은 대문자도 포함

 

Example 1:

Input Output
s = "hello" "holle"

 

Example 2:

Input Output
s = "leetcode" "leotcede"

 

 

문제풀이 코드

class Solution:
def reverseVowels(self, s: str) -> str:
vowels = {'a','e','i','o','u','A','E','I','O','U'}
s = list(s)
i, j = 0, len(s) - 1
while i < j:
# s[i]가 모음 집합에 들어가있고, s[j]는 안들어가있다면 j -= 1 해준다
if s[i] in vowels and s[j] not in vowels:
j -= 1
continue
# s[j]가 모음 집합에 들어가있고, s[i]는 안들어가있다면 i += 1 해준다
elif s[i] not in vowels and s[j] in vowels:
i += 1
continue
# s[i]가 모음 집합에 들어가있고, s[j]도 들어가있다면 s[i]와 s[j]의 위치를 바꾼다
elif s[i] in vowels and s[j] in vowels:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
return ''.join(s)

투포인터로 문제 접근

1. i = 0, j = len(s) -1 로 초기화한다

2. i번째 문자가 모음이고 j번째 문자는 모음이 아닐 때 j = j - 1을 해준다.

3. j번째 문자가 모음이고 i번째 문자는 모음이 아닐 때 i = i + 1을 해준다.

4. i번째 문자가 모음이고 j번째 문자도 모음일 때 s[i]와 s[j]의 자리를 바꿔주고 i = i + 1, j = j - 1을 해준다

5. 반복문이 종료되면 문자열로 변환하여 반환한다.

+ Recent posts