Reverse Vowels of a String - String - Easy - LeetCode
💻 coding

Reverse Vowels of a String - String - Easy - LeetCode

1 min read 216 words
1 min read
ShareWhatsAppPost on X
  • 1The function reverses only the vowels in a given string while maintaining the positions of consonants.
  • 2Examples provided include reversing 'hello' to 'holle' and 'leetcode' to 'leotcede'.
  • 3The algorithm has a time complexity of O(n) and a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The function reverses only the vowels in a given string while maintaining the positions of consonants."

Reverse Vowels of a String - String - Easy - LeetCode

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);
 }
 }
}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 4 June 2020 · 1 min read · 216 words

Part of AskGif Blog · coding

You might also like