LeetCode 68. Text Justification

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Allenlzcoder/article/details/82150202

LeetCode 68. Text Justification

Solution1:我的答案
除了写的比较慢,没有其他很大的问题。。

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string> res;
        int start = 0, size = words.size();
        while (start < size) { //起始坐标<size
            //temp_width是最小字符串长度(单词之间只有1个空格)i临时下标变量
            int temp_width = words[start].size(), i = start;
            string tmp = "";//定义需要被压入vector中的临时string
            while (i + 1 < words.size() && (temp_width + words[i + 1].size() + 1 <= maxWidth)) {
                i++;//下标更新
                temp_width += words[i].size() + 1;//temp_width是最小字符串长度,单词之间仅有一个空格
            }
            // 下面需要把从start到i之间的单词穿起来并压入res中,分类讨论
            if (start == i) {// 1.一行只有一个单词
                if (temp_width == maxWidth) //单词长度恰好是maxWidth
                    res.push_back(words[start]);
                else //单词长度小于maxWidth
                    res.push_back(words[start] + string(maxWidth - temp_width, ' '));
            } else if (i == size - 1 || temp_width == maxWidth) { // 2.最后一行或者恰好满足最大长度
                tmp = words[start];
                for (int j = start + 1; j <= i; j++)
                    tmp = tmp + ' ' + words[j];
                if (i == size - 1)
                    tmp = tmp + string(maxWidth - temp_width, ' ');
                res.push_back(tmp);
            } else {// 3.需要添加多余的空格,最麻烦。。
                int num_spaces_redu = maxWidth - temp_width;//多余的空格数
                int ave_space = num_spaces_redu / (i - start) + 1;//单词间最小空格数
                int residual = num_spaces_redu % (i - start);
                tmp = words[start];
                for (int j = start + 1; j <= i; j++) {
                    if (j - start <= residual)
                        tmp = tmp + string(ave_space + 1, ' ') + words[j];
                    else
                        tmp = tmp + string(ave_space, ' ') + words[j];
                }
                res.push_back(tmp);
            }
            start = i + 1;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/Allenlzcoder/article/details/82150202
今日推荐