反转一个字符串中所有元音
思路一:先预处理找出字符串中所有原因的位置,再两两交换,比较慢一点
1 #345
2 #Runtime: 68 ms
3 #Memory Usage: 16.6 MB
4
5 class Solution(object):
6 def reverseVowels(self, s):
7 """
8 :type s: str
9 :rtype: str
10 """
11 idx = [i for i,x in enumerate(s) if x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u' or x == 'A' or x == 'E' or x == 'I' or x == 'O' or x == 'U']
12 newstr = list(s)
13 l = 0
14 r = len(idx) - 1
15 while l < r:
16 newstr[idx[l]], newstr[idx[r]] = newstr[idx[r]], newstr[idx[l]]
17 l += 1
18 r -= 1
19 return ''.join(newstr)
思路二:两个指针,从开头和结尾向中间扫直至相遇,第一个指针碰到元音时,不断左移第二个指针直到碰到第一个指针或者也遇到元音
1 #345
2 #Runtime: 32 ms
3 #Memory Usage: 15.6 MB
4
5 class Solution(object):
6 def reverseVowels(self, s):
7 """
8 :type s: str
9 :rtype: str
10 """
11 l = list(s)
12 p1 = 0
13 p2 = len(s) - 1
14 vols = {'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'}
15 while p1 < p2:
16 if l[p1] in vols:
17 while p1 < p2:
18 if l[p2] in vols:
19 l[p1], l[p2] = l[p2], l[p1]
20 p2 -= 1
21 break
22 p2 -= 1
23 p1 += 1
24 return ''.join(l)