Reverse Vowels Of A String Problem


Description

LeetCode Problem 345.

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:

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

Example 2:

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

Constraints:

  • 1 <= s.length <= 3 * 10^5
  • s consist of printable ASCII characters.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
    bool isVowel(char c) {
        return (c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') ||
            (c == 'u') || (c == 'A') || (c == 'E') || (c == 'I') ||
            (c == 'O') || (c == 'U');
    }
    string reverseVowels(string s) {
        int i = 0, j = s.size() - 1;
        char c;
        while (i <= j) {
            if ((isVowel(s[i])) && (isVowel(s[j]))) {
               c = s[i];
                s[i] = s[j];
                s[j] = c;
                i ++;
                j --;
            } else {
                if (!isVowel(s[i])) {
                    i ++;
                }
                if (!isVowel(s[j])) {
                    j --;
                }
            }
        }
        return s;
    }
};




Related Posts

Squares Of A Sorted Array Problem

LeetCode 977. Given an integer array nums sorted in non-decreasing...

Sort Array By Parity Problem

LeetCode 905. Given an integer array nums, move all the...

Sort Array By Parity II Problem

LeetCode 922. Given an array of integers nums, half of...

Shortest Distance To A Character Problem

LeetCode 821. Given a string s and a character c...

Reverse Only Letters Problem

LeetCode 917. Given a string s, reverse the string according...

Push Dominoes Problem

LeetCode 838. There are n dominoes in a line, and...