Introduction

Given an input string, reverse the string word by word.

Input: "the sky is blue"
Output: "blue is sky the"

Input: "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Sample Examples

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Approach

There can be an approach based on converting string to Char Array, reverse the array and then reverse each word while cleaning spaces. Another approach can be to use the library methods to split and reverse.

public class Solution {
    public string ReverseWords(string s) {
        if (string.IsNullOrWhiteSpace(s)) {
            return string.Empty;
        }
        return string.Join(" ", s.Split(" ", StringSplitOptions.RemoveEmptyEntries).Reverse());
    }
}
Program to reverse the words