Reverse Words in a String

Reverse Words in a String 

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

For example,
Given s = "the sky is blue",
return "blue is sky the".

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

Answer:

void re(int start, int end, string &s)
{
    int n = end - start + 1;
    for (int i = start; i < start + n / 2; i++)
    {
        char c = s[i];
        s[i] = s[end - i + start];
        s[end - i + start] = c;
    }
}

void reverseWords(string &s)
{
    int n = s.length();
    int flag = 1;
    int start = 0;
    int end = 0;

    re(0, n - 1, s);

    if (n == 1)
    {
        if (s[0] == ' ')
        {
            s = s.substr(0, 0);
        }
    }
    else
    {
        for (int i = 0; i < n; i++)
        {
            if (s[i] == ' ')
            {
                if (flag == 0)
                {
                    re(start, end - 1, s);
                    s[end] = ' ';
                    start = ++end;
                }
                flag = 1;
            }
            else
            {
                s[end++] = s[i];
                flag = 0;
            }
        }
        if (start != end)
        {
            re(start, end - 1, s);
        }
        s = s.substr(0, end);
        if (s[end - 1] == ' ')
        {
            s = s.substr(0, end - 1);
        }
    }
}
原文地址:https://www.cnblogs.com/ich1990/p/3636308.html