头图

title: Daily Practice (31): Flip the word order

categories:[Swords offer]

tags:[Daily practice]

date: 2022/03/05


Daily practice (31): Flip the word order

Enter an English sentence, flip the order of the words in the sentence, but not change the order of the characters within the words. For simplicity, punctuation marks are treated like ordinary letters. For example, input the string "I am a student. ", then output "student. a am I".

Example 1:

Input: "the sky is blue"

Output: "blue is sky the"

Example 2:

Type: "hello world!"

Output: "world! hello"

Explanation: The input string can contain extra spaces before or after it, but the reversed characters cannot.

Example 3:

Enter: "a good example"

Output: "example good a"

Explanation: If there is an extra space between two words, reduce the space between the reversed words to only one.

illustrate:

Characters without spaces form a word.

The input string can contain extra spaces before or after it, but the reversed characters cannot.

If there is an extra space between two words, reduce the space between the reversed words to only one.

Source: LeetCode

Link: https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof

Method 1: Template code

Method source: https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/solution/yi-ge-mo-ban-shua-bian-suo-you-zi- fu-chu-x6vh/

Thought analysis

My usual practice for this kind of problem is also the core idea, which is to first take out all the strings in the sentence and put them into the string array, and then operate the strings in the array and then reconnect them.

To analyze according to the requirements of the topic

The idea of traversing a sentence to get a string is to put it into a temporary string when encountering a character, and output the temporary string when encountering a space or punctuation (if there is a punctuation), and clear it.

template code

It should be noted that these questions can be divided into two categories, one with leading or trailing spaces, and the other without leading and trailing spaces.

Template 1. If there are spaces before and after, it must be judged that the temporary string is not empty before it can be output, otherwise an empty string will be output

s += " ";    //这里在最后一个字符位置加上空格,这样最后一个字符串就不会遗漏
string temp = "";   //临时字符串
vector<string> res; //存放字符串的数组
for (char ch : s) { //遍历字符句子
    if (ch == ' ') {//遇到空格
        if (!temp.empty()) {     //有前后置空格,需要判断临时字符串非空,反之可以去掉此判断
            res.push_back(temp);
            temp.clear();        //清空临时字符串
        }
    } else {
        temp += ch;
    }
}

Template 2. There is no space before and after it does not need to judge the empty string

s += " ";    //这里在最后一个字符位置加上空格,这样最后一个字符串就不会遗漏
string temp = "";   //临时字符串
vector<string> res; //存放字符串的数组
for (char ch : s) { //遍历字符句子
    if (ch == ' ') {//遇到空格
        res.push_back(temp);
        temp.clear();        //清空临时字符串
    } else {
        temp += ch;
    }
}

This question uses: template 1 + reverse the entire character array + reconnect

string reverseWords(string s) {
    s += " ";    //这里在最后一个字符位置加上空格,这样最后一个字符串就不会遗漏
    string temp = "";   //临时字符串
    vector<string> res; //存放字符串的数组
    for (char ch : s) { //遍历字符句子
        if (ch == ' ') {//遇到空格
            if (!temp.empty()) {     //有前后置空格,需要判断临时字符串非空,反之可以去掉此判断
                res.push_back(temp);
                temp.clear();        //清空临时字符串
            }
        } else {
            temp += ch;
        }
    }
    s.clear();
    reverse(res.begin(), res.end());
    for (string &str : res) {
        s += str + ' ';
    }
    s.pop_back();    //去除最后一个空格
    return s;
}

Method 2: Double pointer

Algorithm flow:

  • We use two pointers l, r to help select each word
  • In each loop, first remove the spaces on the right side of all words, get the rightmost subscript r of a word, and then get the leftmost subscript l of the word
  • Then add the word s.substr(l + 1, r - l) to ret, don't forget to add a space
  • Finally, remove the extra spaces ret.pop_back()
string reverseWords(string s) {
    int l = 0, r = s.size() - 1;
    string ret;
    while (r >= 0) {
        while (r >= 0 && s[r] == ' ') {
            --r;    //清除单词右侧空格
        }
        if (r < 0) {
            break;
        }
        for (l = r; l >=0 && s[l] != ' '; --l);    //取单词
        ret += (s.substr(l + 1, r - l) + " ");
        r = l;
    }
    if (ret.size()) {
        ret.pop_back();  //去除最后一个空格
    }
    return ret;
}

Method 3: API istringstream

//栈
string reverseWords(string s) {
    stack<string> stk;
    string res, str;
    istringstream ss(s);
    while (ss >> str) {    //入栈
        stk.push(str),stk.push(" ");
    }
    if (!stk.empty()) {
        stk.pop();
    }
    while (!stk.empty()) {//出栈
        res += stk.top(), stk.pop();
    }
    return res;
}
//非栈
string reverseWords(string s) {
    istringstream ss(s);
    string res, str;
    while ( ss >> str) {
        res = str + ' ' + res;
    }
    return res.substr(0, res.size() - 1);
}

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记