Skip to content

Latest commit

 

History

History
66 lines (55 loc) · 1.25 KB

File metadata and controls

66 lines (55 loc) · 1.25 KB

345. Reverse Vowels of a String

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".

Solutions (Python)

1. Two Pointers

class Solution:
    def reverseVowels(self, s: str) -> str:
        s = list(s)
        vowels = "aiueoAIUEO"
        i = 0
        j = len(s) - 1
        while i < j:
            while i < j and s[i] not in vowels:
                i += 1
            while i < j and s[j] not in vowels:
                j -= 1
            s[i], s[j] = s[j], s[i]
            i += 1
            j -= 1
        return ''.join(s)

Solutions (Ruby)

1. Two Pointers

# @param {String} s
# @return {String}
def reverse_vowels(s)
    vowels = "aiueoAIUEO"
    i, j = 0, s.length - 1

    while i < j
        while i < j and not vowels.include?(s[i])
            i += 1
        end
        while i < j and not vowels.include?(s[j])
            j -= 1
        end

        s[i], s[j] = s[j], s[i]

        i += 1
        j -= 1
    end

    return s
end