LeetCode - Reverse Vowels of a String(345)

marafo·2021년 6월 5일

String - Easy

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.

Example 1:

Input: s = "hello"
Output: "holle"

Example 2:

Input: s = "leetcode"
Output: "leotcede"

Constraints:

∙ 1 <= s.length <= 3 * 105
∙ s consist of printable ASCII characters.


Runtime : 112ms / Memory : 14.8 MB

from collections import deque

class Solution:
    def reverseVowels(self, s: str) -> str:
        result = ''
        vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'I', 'E', 'O', 'U']
        reverse = deque([])
        
        for i in range(len(s) - 1,  -1, -1):
            if vowels.count(s[i]) == 1:
                reverse.append(s[i])
        
        for i in range(len(s)):
            if vowels.count(s[i]) == 0:
                result += s[i]
            else:
                result += reverse[0]
                reverse.popleft()
        
        return result

참고 솔루션
Runtime : 44ms / Memory : 14.8 MB

class Solution(object):
    def reverseVowels(self, s):

        vowels = set(list('aeiouAEIOU'))
        s = list(s)
        front = 0
        end = len(s)-1
        while front < end:
            if s[front] in vowels:
                while not s[end] in vowels and front < end:
                    end -= 1
                s[front], s[end] = s[end], s[front]
                end -= 1
            front += 1

        return ''.join(s)

참고
https://www.codeleading.com/article/63684649616/

profile
프론트 개발자 준비

0개의 댓글