Search

Reverse Vowels of a String

문제 설명 : 제공된 문자열의 내부에 있는 모음을 서로 뒤집어 새로운 문자열을 반환
풀이 방법
문자열 양끝에 커서를 설정하여, 모음일 때 swap 처리하였다.
시간복잡도 : O(N)O(N)
성공 코드
# O(N + N) -> O(N) class Solution: def reverseVowels(self, s: str) -> str: result = list(s) left, right = 0, len(s) - 1 # 모음 확인 table = set(('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')) # 양쪽 커서가 만날때까지 -> O(N) while left <= right: # 모음일 경우 변경 if s[left] in table and s[right] in table: result[left], result[right] = result[right], result[left] left += 1 right -= 1 continue if s[left] not in table: left += 1 if s[right] not in table: right -= 1 # O(N) return ''.join(result)
Python
복사