Thursday, December 24, 2020

Reverse Vowels of a String

Problem: Write a function that takes a string as input and reverse only the vowels of a string.

Example:

Input: "nishant"
Output: "nashint"


Approach: Problem is very easy to solve by using the two pointers string reverse approach. Here we just need to take care of some boundary conditions which we can understand by just looking at the code.


Implementation in C#:

        public string ReverseVowels(string s)

        {

            if (s?.Length <= 1)

            {

                return s;

            }

            char[] result = new char[s.Length];

            int i = 0, j = s.Length - 1;

            for (; i < j;)

            {

                while (i < s.Length && !IsVowel(s[i]))

                {

                    result[i] = s[i];

                    ++i;

                }

                while (j >= 0 && !IsVowel(s[j]))

                {

                    result[j] = s[j];

                    --j;

                }

                if (i < j)

                {

                    result[i] = s[j];

                    result[j] = s[i];

                    ++i;

                    --j;

                }               

            }

            if (i == j)

            {

                result[i] = s[i];

            }

            return new string(result);

        }


        private bool IsVowel(char ch)

        {

            ch = char.ToLower(ch);

            return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';

        }


Complexity: O(n)

No comments:

Post a Comment