题目:编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例:
输入: "hello"
输出: "holle"
输入: "leetcode"
输出: "leotcede"
思路:这道题其实不难,但是列表问题中的边界条件特别容易被忽略,很容易访问超限,一定要注意!!!
代码:中间有一个地方:while (left < len(s)) and (right > 0) and (s_lst[left] not in tmp)这一句,三个条件是与的关系,如果第一个条件不成立,则不会再去判断后面的条件,所以列表超限问题也就被规避了,如果将(s_lst[left] not in tmp)放在第一个位置,则又会产生访问超限的错误。其他条件判断关系也是这样,如果前面的条件已经足够做出判断,则不会继续对后面的条件进行判断。
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
if len(s) < 2:
return s
else:
left = 0
right = len(s) - 1
tmp = 'aeiouAEIOU'
s_lst = list(s)
while left < right and left < len(s) and right > 0:
while (left < len(s)) and (right > 0) and (s_lst[left] not in tmp):
left += 1
while (left < len(s)) and (right > 0) and (s_lst[right] not in tmp):
right -= 1
if left < right and left < len(s) and right > 0:
if not s_lst[left] == s_lst[right]:
s_lst[left], s_lst[right] = s_lst[right], s_lst[left]
left += 1
right -= 1
return ''.join(s_lst)