代码改变世界

[LeetCode] 345. Reverse Vowels of a String_Easy tag:Two Pointers

2018-08-17 03:37  Johnson_强生仔仔  阅读(187)  评论(0编辑  收藏  举报

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Input: "hello"
Output: "holle"

Example 2:

Input: "leetcode"
Output: "leotcede"

Note:
The vowels does not include the letter "y".

 

思路用一个indexs来存是vowels的index, 然后分别对调index的l, r, 最后返回字符串. Note: array可以modify, 但是string不能, 所以要将string变为array, 最后再转换为string.

 

Code

class Solution:
    def reverseVowels(self, s):
        indexs, s, vowels, length = [], list(s), "euioaEUIOA", len(s)
        
        for i in range(length):
            if s[i] in vowels:
                indexs.append(i)
        l2 = len(indexs)
        for j in range(l2//2):
            l, r = indexs[j], index[l2-j-1]
            s[l], s[r] = s[r], s[l]
        return "".join(s)