forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_vowel.py
More file actions
43 lines (34 loc) · 1.06 KB
/
reverse_vowel.py
File metadata and controls
43 lines (34 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""
Reverse Vowels of a String
Given a string, reverse only the vowels while keeping all other characters
in their original positions.
Reference: https://leetcode.com/problems/reverse-vowels-of-a-string/
Complexity:
Time: O(n) where n is the length of the string
Space: O(n) for the character list
"""
from __future__ import annotations
def reverse_vowel(text: str) -> str:
"""Reverse only the vowels in a string.
Args:
text: The input string.
Returns:
A new string with vowels reversed.
Examples:
>>> reverse_vowel("hello")
'holle'
"""
vowels = "AEIOUaeiou"
left, right = 0, len(text) - 1
characters = list(text)
while left < right:
while left < right and characters[left] not in vowels:
left += 1
while left < right and characters[right] not in vowels:
right -= 1
characters[left], characters[right] = (
characters[right],
characters[left],
)
left, right = left + 1, right - 1
return "".join(characters)