Tuesday, September 22, 2020

Reverse Words in a String - 2

Problem: This is similar to Reverse words in a sentence but with some extra conditions. Here is what is more -

  1. Reversed string should not contain leading or trailing spaces.
  2. Reduce multiple spaces between two words to a single space in the reversed string.
Example:

Input: "  Nishant Saxena   examples   "
Output: "examples Saxena Nishant"


Approach: Same as the original problem. We just need to take care of leading, trailing and multiple continuous spaces. Using Trim() and one self written method we can make the string which can be processed successfully by original ReverseWords method.


Implementation in C#:

        public string ReverseWords(string s)
    {
        if (string.IsNullOrEmpty(s))
        {
            return s;
        }
        char[] sArr = s.Trim().ToCharArray();
        int end = this.RemoveDupSpaces(sArr);
        this.Reverse(sArr, 0, end - 1);
        int i = 0, j = 0;
        while(j < end)
        {
            while(j < end && sArr[j] != ' ')
            {
                ++j;
            }
            this.Reverse(sArr, i, j - 1);
            j = j + 1;
            i = j;
        }      
        return new string(sArr, 0, end);
    }

    private void Reverse(char[] sArr, int start, int end)
    {
        while (start < end)
        {
            char temp = sArr[start];
            sArr[start++] = sArr[end];
            sArr[end--] = temp;
        }
    }

    private int RemoveDupSpaces(char[] sArr)
    {
        int j = 0;
        for (int i = 0; i < sArr.Length; ++i)
        {
            if (sArr[i] != ' ' || sArr[i  - 1] != ' ')
            {
                sArr[j++] = sArr[i];
            }
        }
        return j;
    }


Complexity: O(n)

No comments:

Post a Comment