This article is participating in the nuggets team number online activity, click to see the dachang spring recruiting positions

1. Title Description

Write a function that takes a string as input and inverts the vowels in that string.

Example 1:

Input:"hello"Output:"holle"
Copy the code

Example 2:

Input:"leetcode"Output:"leotcede"
Copy the code

Second, train of thought analysis

  1. Create two lists,resstoreAll characters in s.tmpstoreThe vowel character in s.
  2. traverseresIf there are vowel characters, usetmp.pop()Instead.

In this case, the TMP list is like a stack, and the order of the vowel characters in the string is subtly reversed by using the feature of the stack first in and then out.

AC code

class Solution:
    def reverseVowels(self.s: str) - >str:
        letter='aeiouAEIOU'
        res=[]
        tmp=[]
        for i in s:
            res.append(i)
            if i in letter:
                tmp.append(i)
        for i in range(len(res)):
            if res[i] in letter:
                res[i]=tmp.pop()
        return "".join(res)
Copy the code

The output is:

Four,

The problem can skillfully use the data structure stack of the first in after the characteristics of the problem to answer the problem, the idea to solve the problem wide, skilled use of several data structure characteristics to answer the problem.