Sword Finger Offer 58-I. Reverse Word Order (C++) Double Pointer

Enter an English sentence, reverse the order of the words in the sentence, but the order of the characters in the word does not change. 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:

输入: "the sky is blue"
输出: "blue is sky the"

Example 2:

输入: "  hello world!  "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。

Example 3:

输入: "a good   example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

Description:

No space characters form a word.
The input string can contain extra spaces before or after it, but the reversed characters cannot be included.
If there is an extra space between two words, reduce the space between the words after inversion to only one.

Note: This question is the same as the 151 question on the main website: https://leetcode-cn.com/problems/reverse-words-in-a-string/

Double pointer

Algorithm analysis:

Traverse the string s in reverse order, record the left and right index boundaries i, j
of the word ; each time the boundary of a word is determined, it is added to the word list res;
finally, the word list is spliced ​​into a string and returned.

class Solution {
    
    
public:
    string reverseWords(string s) {
    
    
        string res;
        int n = s.size();
        if(n == 0) return res;
        int right = n - 1;
        while(right >= 0){
    
    
            //从后往前寻找第一字符
            while(right >= 0 && s[right] == ' ') right--;//s[right] != ' '
            if(right < 0) break;

            //从后往前寻找第一个空格
            int left = right;//指针对齐
            while( left >= 0 && s[left] != ' ' ) left--;//得到s[left] == ' ' 

            //添加单词到结果
            res += s.substr(left + 1, right - left);
            res += ' ';

            //继续往前分割单词
            right = left;//指针对齐
        }
        //去除最后一个字符空格
        if (!res.empty()) res.pop_back();//弹出最后的空格
        return res;
    }
};

Complexity analysis:

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_30457077/article/details/114846682