Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 151. Reverse Words in a String

Rain Hu

151. Reverse Words in a String


一、題目

Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Example 1:

Example 2:

Example 3:

Constraints:

Follow-up: If the string data is mutable in your language, can you solve it int-place with O(1) extra space?


二、分析

三、解題

1. split function

string reverseWords(string s) {
    vector<string> svec = split(s, ' ');    // 以空白字元作為分隔
    string res;
    for (int i = svec.size()-1; i >= 0; i--) {
        res = res + " " + svec[i];      // 將陣列反過來組合成字串
    }
    res = res.substr(1);        // 移除多出來的空白字元
    return res;
}
vector<string> split(string& s, char del) {
    stringstream ss(s);
    vector<string> res;
    string item;
    while (getline(ss, item, del)) {
        if (!item.empty()) res.push_back(item); // 注意,空白不加到陣列中
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 947. Most Stones Removed with Same Row or Column
Next
[LeetCode] 23. Merge k Sorted Lists