LeetCode 1592. 重新排列单词间的空格 双指针

地址 https://leetcode-cn.com/problems/rearrange-spaces-between-words/

给你一个字符串 text ,该字符串由若干被空格包围的单词组成。
每个单词由一个或者多个小写英文字母组成,并且两个单词之间至少存在一个空格。
题目测试用例保证 text 至少包含一个单词 。

请你重新排列空格,使每对相邻单词之间的空格数目都 相等 ,并尽可能 最大化 该数目。
如果不能重新平均分配所有空格,请 将多余的空格放置在字符串末尾 ,
这也意味着返回的字符串应当与原 text 字符串的长度相等。

返回 重新排列空格后的字符串 。

 

示例 1:

输入:text = "  this   is  a sentence "
输出:"this   is   a   sentence"
解释:总共有 9 个空格和 4 个单词。
可以将 9 个空格平均分配到相邻单词之间,相邻单词间空格数为:9 / (4-1) = 3 个。
示例 2:

输入:text = " practice   makes   perfect"
输出:"practice   makes   perfect "
解释:总共有 7 个空格和 3 个单词。7 / (3-1) = 3 个空格加上 1 个多余的空格。多余的空格需要放在字符串的末尾。
示例 3:

输入:text = "hello   world"
输出:"hello   world"
示例 4:

输入:text = "  walks  udp package   into  bar a"
输出:"walks  udp  package  into  bar  a "
示例 5:

输入:text = "a"
输出:"a"
 

提示:

1 <= text.length <= 100
text 由小写英文字母和 ' ' 组成
text 中至少包含一个单词

算法1
双指针分离单词和统计空格
然后构造答案

C++ 代码

class Solution {
public:
    string reorderSpaces(string text) {
        vector<string> S;
        int i=0;
        int c=0;
        while(i<text.size()){
            while(i<text.size() && text[i]==' ') ++i;
            string x;
            while(i<text.size() && text[i]!=' ') x+=text[i],++i;
            c+=x.size();
            if(x.size()) S.push_back(x);
        }
        string ans;
        int r=text.size()-c;
        if(S.size()==1){
            ans += S.front();
            ans += string(r,' ');
        }else{
            int a=r/(S.size()-1);
            int b=r%(S.size()-1);
            for(int j=0;j<S.size();++j){
                if(j)  ans += string(a,' ');
                ans += S[j];
            }
            if(b)  ans += string(b,' ');
        }
        return ans;
    }
};
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/13707613.html