Python LeetCode(345.反转字符串中的元音字母)
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入: “hello”
输出: “holle”
示例 2:
输入: “leetcode”
输出: “leotcede”
说明:
元音字母不包含字母"y"。
Solution:(同样地设置头、尾两个指针,当指针对应的元素为元音字母时进行交换(这里对字符串转换成列表进行操作,然后在转换成字符串返回))
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
i, j = 0, len(s)-1
word_list = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
s_list = list(s)
while i < j:
while s_list[i] not in word_list and i < j:
i += 1
while s_list[j] not in word_list and i < j:
j -= 1
s_list[i], s_list[j] = s_list[j], s_list[i]
i += 1
j -= 1
return ''.join(s_list)
solution = Solution()
print(solution.reverseVowels('hello'))
holle