Loading

LeetCode problem#345

Reverse Vowels of a String

Solved in 1 languageC#

Solve it on LeetCode(opens in a new tab)

Solution

37 lines
1public class Solution {
2    bool IsVowel(char c)
3    {
4        // or you could do
5        // return "aAeEiIoOuU".Contains(c);
6        return c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U';
7    }
8
9    public string ReverseVowels(string s) {
10        int i = 0;
11        int j = s.Length - 1;
12        char[] chars = s.ToCharArray();
13
14        while (i < j)
15        {
16            if (!IsVowel(chars[i]))
17            {
18                i++;
19            }
20            else if (!IsVowel(chars[j]))
21            {
22                j--;
23            }
24            else if (IsVowel(chars[i]) && IsVowel(chars[j]))
25            {
26                char temp = chars[i];
27                chars[i] = chars[j];
28                chars[j] = temp;
29
30                i++;
31                j--;
32            }
33        }
34
35        return new string(chars);
36    }
37}

Want a walkthrough of this C# solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.