字符串单词翻转

题目描述

给定一个字符串,逐个翻转字符串中的每个单词。

说明:

无空格字符构成一个 单词 。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
 

示例 1:

输入:"the sky is blue"
输出:"blue is sky the"
示例 2:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string

解题思路

可以使用栈或者双端队列作为数据结构存储单词,将其反向拼接为需要的结果,但是空间复杂度为 o(n),如果要求 o(1)的复杂度,只能再string 本身进行反转覆盖,并且同时去除重复空格,下面代码是o(1)的解法,使用双指针思想记录原始字符串的末尾和翻转后的字符串的开始位置。

string reverseWords(string s) {
        int tail = s.size()-1;
        int end = tail;
        int gip, i;
        while(end >= 0) {
            gip = 0;
            string word = "";
            for(i = 0; i <= end; i++) {
                if(s[i] == ' ' && word != "") {
                    while(s[i++] == ' ') {
                        gip ++;
                    }
                    break;
                }
                if(s[i] == ' ') {
                    gip ++;
                    continue;
                }
                word += s[i];
                gip++;
            }
            for(i = gip; i <= end; i++) s[i-gip] = s[i];
            end -= gip;
            i = tail-word.size()+1;
            tail = i-2;
            if(i>0) s[i-1] = ' ';
            for(auto c : word) s[i++] = c;
        }
        s.erase(0, tail+2);
        return s;
    }
原文地址:https://www.cnblogs.com/zz-zhang/p/13926822.html