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 do not include the letter "y".
Solution:
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode.AskGif.Easy.String
{
public class ReverseVowelsSoln
{
public string ReverseVowels(string s)
{
int i = 0;
int j = s.Length - 1;
var strChar = s.ToCharArray();
while (i < j)
{
if (!IsVowel(s[i]))
{
i++;
continue;
}
if (!IsVowel(s[j]))
{
j--;
continue;
}
char temp = strChar[j];
strChar[j] = s[i];
strChar[i] = temp;
i++;
j--;
}
return new string(strChar);
}
private bool IsVowel(char v)
{
bool isVowel = false;
switch (v)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':isVowel = true;
break;
}
return isVowel;
}
}
}
Time Complexity: O(n)
Space Complexity: O(1)
Unit Tests:
using LeetCode.AskGif.Easy.String;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace CodingUnitTest.Easy.String
{
[TestClass]
public class ReverseVowelsSolnTests
{
[TestMethod]
public void ReverseVowelsSoln_First()
{
var a = "hello";
var output = "holle";
var res = new ReverseVowelsSoln().ReverseVowels(a);
Assert.AreEqual(res, output);
}
[TestMethod]
public void ReverseVowelsSoln_Second()
{
var a = "leetcode";
var output = "leotcede";
var res = new ReverseVowelsSoln().ReverseVowels(a);
Assert.AreEqual(res, output);
}
}
}



