题目:
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入: “hello”
输出: “holle”
示例 2:
输入: “leetcode”
输出: “leotcede”
说明:
元音字母不包含字母"y"。
思路1:
将元音字母存到列表,遍历字符串,查找列表,存储元音字母索引和元音字母,反转字符串,利用索引赋值
class Solution:
def reverseVowels(self, s: str) -> str:
if s=="":
return ""
listy=['a','o','e','i','u','A','O','E','I','U']
queue=[]
temp_index=[]
for i in range(len(s)):
if s[i] in listy:
queue.append(s[i])
temp_index.append(i)
queue.reverse()
j=0
s=list(s)
for i in temp_index:
s[i]=queue[j]
j+=1
s="".join(s)
return s
虽然通过了,但是代码不够美观,更谈不上什么算法,参考其他的人算法。
思路2:本题还有另外一种思路,那就是two pointer。一个指针从前往后扫描,一个指针从后往前扫描,遇到元音字母时进行交换,直到两个指针相遇,算法终止。算法复杂度同样是O(N)。
定义数组的两个索引变量i,j.
当头指针和尾指针同时为元音字母时,change,两个指针加一;
当头指针和尾指针同时都不为元音字母时,两个指针加一;
当头指针为元音字母,尾指针不为元音字母时,尾指针加一;
当头指针不为元音字母,尾指针为元音字母时,头指针加一;
class Solution:
def reverseVowels(self, s: str) -> str:
if s=="":
return ""
listy=['a','o','e','i','u','A','O','E','I','U']
s=list(s)
# for i in range(len(s)):
i,j=0,0#two pointer
while i<(len(s)-j-1):
if s[i] in listy and s[-1-j] in listy:
s[i],s[-1-j]=s[-1-j], s[i]
i+=1
j+=1
elif s[i] in listy and s[-1-j] not in listy:
j+=1
elif s[i] not in listy and s[-1-j] in listy:
i+=1
else:
i+=1
j+=1
# print(s)
# print(i,j)
return "".join(s)