1.题目
找到字符串中的元音,翻转如下:
Given s = "leetcode", return "leotcede".
2.代码实现:
class Solution: def reverseVowels(self, s: str) -> str: dict = {'a','e','i','o','u','A','E','I','O','U'} pol = 0 #最小字符的下标 por = len(s)-1 #最大字符的下标 s_ = list(s) #转换为列表 while pol <= por: if s_[pol] in dict and s_[por] in dict: s_[pol],s_[por] =s_[por],s_[pol] pol+=1 por-=1 elif s_[por] not in dict: por-=1 else: pol+=1 else: return ''.join(s_)
3.注意事项:
1.这个判断过程必然是通过哈希最快,也就是字典类型最方便
2.不同的判断结果导致的双指针推进速度不同,但是每次都判断,又会降低速度,所以使用两个变量保存判断结果
3.字符串转列表 :list(s),列表转字符串: ‘’.join(s_)