LeetCode 0345. Reverse Vowels of a String【Easy】【Python】
The title
English title Link
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello"
Output: "holle"
Copy the code
Example 2:
Input: "leetcode"
Output: "leotcede"
Copy the code
Note: The vowels does not include the letter “y”.
translation
Chinese title Link
Write a function that takes a string as input and inverts the vowels in that string.
Example 1:
Input:"hello"Output:"holle"
Copy the code
Example 2:
Input:"leetcode"Output:"leotcede"
Copy the code
Note: Vowels do not contain the letter “y”.
Train of thought
Double pointer
The left pointer looks for vowels from left to right and the right pointer looks for vowels from right to left.
Since strings cannot be changed, you need to use a list instead.
Python code
class Solution(object):
def reverseVowels(self, s):
""" :type s: str :rtype: str """
left, right = 0, len(s)- 1 # Simultaneous assignment
vowels = 'aeiou'
string = list(s) # String cannot be changed, so change to list
while left < right:
if string[left].lower() not in vowels: # lower is lowercase
left += 1
elif string[right].lower() not in vowels:
right -= 1
else:
string[left], string[right] = string[right], string[left]
left += 1
right -= 1
return ' '.join(string) Generates a new string by concatenating the elements in the string with the specified characters
Copy the code
The code address
Making a link