Offer] [prove safety reversing the order of the word string; the "I am a student.", After inverted to "student a am I.". That word sentence inverted position, without changing the internal structure of the word

Title Description

Write function, "I am a student.", After flipping as "student. A am I". That word sentence inverted position, without changing the internal structure of the word

Thinking

There are two ideas for the body, much the same.
Thinking a:
1- word to be inverted internal (result: the I mA .tneduts A)
(. The results for the student a am I) 2- and the results of the first step in the overall inversion
idea II:
1- entirely turned Advancement (result: the I .tneduts a mA)
2- the results of the first step before and after the internal word exchange (results student a am I.)

Code

The code is a code that ideas

class Solution {
public:
    string ReverseSentence(string str) {
        char* st = &str[0], * end = &str[0], * ptr = &str[0];
        while (*ptr++ != '\0') {
            if (*ptr == ' '  ||  *ptr == '\0') {
                end = ptr - 1;
                while (st < end) { //进行单词内部交换
                    swap(*st++, *end--);
                }
                st = end = ptr+1;
            }
        }
        st = &str[0];
        end = ptr - 2;
        while (st<end) {//进行整体的前后交换翻转
            swap(*st++, *end--);
        }
        return str;
    }
};
Published 57 original articles · won praise 28 · views 4110

Guess you like

Origin blog.csdn.net/weixin_41747893/article/details/104762279