Sword Finger Offer 58-I Reverse word order C++


2020/2/5 Second brush
substr (string, interception start position, interception length)


Title description

Insert picture description here

Solution isringstream

istringstream method .

class Solution {
    
    
public:
    string reverseWords(string s) {
    
    
        if(s.size() == 0) return "";
        stack <string> stk;
        string tem, ans;
        istringstream ss(s);
        while(ss >> tem) {
    
    
            stk.push(tem);
            stk.push(" ");
        }
        if(!stk.empty()) stk.pop();
        while(!stk.empty()) {
    
    
            ans += stk.top();
            stk.pop();
        }
        return ans;
    }
};

Obviously, we use the stack to reverse all the letters, and then remove the extra space. Since it is more convenient to remove the top of the stack, we first push the string and then the space.
I don’t understand the time complexity and space complexity, so I'll take a second look at it.
In fact, it can be done without using a stack
. Just stuff the letters to the front every time, and finally remove the extra spaces in the first time.

class Solution {
    
    
public:
    string reverseWords(string s) {
    
    
        string tem, ans;
        istringstream ss(s);
        while(ss >> tem) {
    
    
            ans = tem + ' ' + ans;
        }
        return ans.substr(0, ans.size() - 1);
    }
};

The second space complexity seems to be much higher. It
Insert picture description here
Insert picture description here
may be a problem of using substr, so I changed it to ans. pop_back and try it.

Double pointer method

As we all know, this kind of question can definitely start with the double pointer
j starting from the last subscript, find a character that is not a space, then define an i to search forward from j-1 until a space is found, and put the characters in this space Enter the answer. Then let j = i and continue to look forward.
ps: Note that there is no space before the last character. At this time, when i reaches 0, it must stop.

class Solution {
    
    
public:
    string reverseWords(string s) {
    
    
        if(s.size() == 0) return "";
        int j = s.size() - 1;
        string ans;
        for(;j >= 0; --j) {
    
    
            //跳过空格
            if(s[j] == ' ') continue;
            int i = j - 1;
            while(i >= 0 && s[i] != ' ') i--;
            //i + 1 到 j组成一个单词
            for(int k = i + 1; k <= j; k ++) ans.push_back(s[k]);
            //push_back添加一个字符
            ans.push_back(' ');
            j = i;
        }
        if(s.size() > 0) return ans.substr(0, ans.size() - 1);
        return "";
    }
};

Time complexity O(N)
Space complexity O(N)

Guess you like

Origin blog.csdn.net/qq_42883222/article/details/112643558