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

Find K Closest Elements Problem

LeetCode 658. Given a sorted integer array arr, two integers...

Count Binary Substrings Problem

LeetCode 696. Give a binary string s, return the number...

String Compression Problem

LeetCode 443. Given an array of characters chars, compress it...

Shortest Unsorted Continuous Subarray Problem

LeetCode 581. Given an integer array nums, you need to...

Reverse Words In A String III Problem

LeetCode 557. Given a string s, reverse the order of...

Reverse String II Problem

LeetCode 541. Given a string s and an integer k,...