Flip the word order column - the sword refers to the offer

Using the flip function, first invert the entire string, and then use the pp and p pointers to determine the position of the word and invert one by one.
The details should consider the space in front of the string, multiple consecutive spaces in the string, and the last word of the string.

string reverse(string str, int left, int right)
{
    if (left<0 || right > str.length() - 1) {
        return "";
    }
    while (left < right) {
        char tmp;
        tmp = str[left];
        str[left] = str[right];
        str[right] = tmp;
        left++;
        right--;
    }
    return str;
}
string ReverseSentence(string str) {
    int left = 0;
    int right = str.length() - 1;
    str = reverse(str, left, right);
    int p = 0, pp = 0;
    //去掉开头的空格
    while (str[p] != '\0'&& str[p] == ' ') {
        p++;
    }
    pp = p;
    while (p < str.length()) {
        p++;
        if (str[p] == ' ' || str[p]== '\0') {
            str = reverse(str, pp, p-1);
            while (str[p] != '\0'&& str[p] == ' ') {
                p++;
            }
            pp = p;
        }
    }
    return str;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325899382&siteId=291194637
Recommended