Huawei: reverse word sentence

I. Description of the problem

Here Insert Picture Description

Second, problem-solving ideas

Obviously, the word used to save the stack pointer in double resolved.
First remove the leading space character string
from beginning to end scanning string, a space to differentiate words
each time to find a word, the inner pressure of a space on the stack
after a scanned word pointer as the new starting point fast, so slow and equally fast pointer to the pointer position, and even if slow pointer as a new starting point, repeat the process until the end of the

Third, the problem-solving Code

#include <iostream>
#include <string>
#include <stack>
using namespace std;

int main()
{
    string str;
    while (getline(cin, str))
    {
        long rear = 0, prior = 0;
        long len = str.length();
        stack<string> s;
        while (rear < len && str[rear] != '\0')
        {
            while (rear < len && str[rear] == ' ')
            {
                rear++;
            }
            prior = rear;
            while (prior < len && str[prior] != ' ')
            {
                prior++;
            }
            if (rear == len)
                break;
            string tmp_str = str.substr(rear, prior - rear);
            s.push(tmp_str);
            s.push(" ");
            rear = prior;
        }
        s.pop();
        while (!s.empty())
        {
            cout << s.top();
            s.pop();
        }
        cout << endl;
    }
    return 0;
}

There are more, using the cinmethod encountered an input string is returned in a space

#include <iostream>
#include <string>
#include <stack>
using namespace std;

int main()
{
    string str;
	stack<string> s;
    while (cin >> str)
    {
        s.push(str);
		s.push(" ");
    }
	s.pop();
	while(!s.empty()){
		cout << s.top();
		s.pop();
	}
    return 0;
}

Fourth, operating results

Here Insert Picture Description

Published 30 original articles · won praise 3 · Views 815

Guess you like

Origin blog.csdn.net/weixin_44587168/article/details/105334875