LeetCode 68. Text Justification

本文介绍了一种文本对齐算法的实现方式,该算法能够将一组单词按指定宽度均匀对齐,形成美观的段落布局。通过对每行文本中单词间的空格进行智能分配,确保文本整体视觉效果的一致性和美观性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This is actually not the LeetCode version answer. But I think this is more likely in real word.

The Code is copied from the EPI. 大哭 I have no clue to solve this problem at the first sight.

#include <string>
#include <vector>
#include <iostream>
#include <cmath>
using namespace std;

/*
  Example:
  words = ["This", "is", "an", "example", "of", "text", "justification"]
  L : 16
  return 
  [
   "This    is    an",
   "example  of text",
   "justification.  "
  ]
*/
string JoinALineWithSpace(vector<string>& words, int start, int end, int numSpaces) {
  size_t num_words_curr_line = end - start + 1;
  string line;
  for(int i = start; i < end; ++i) {
    line += words[i];
    --num_words_curr_line;
    size_t num_curr_space = ceil(static_cast<double>(numSpaces)/num_words_curr_line);
    line.append(num_curr_space, ' ');
    numSpaces -= num_curr_space;
  }
  line += words[end];
  line.append(numSpaces, ' ');
  return line;
}
vector<string> fullJustify(vector<string>& words, int maxWidth) {
  int maxLen = 0;
  for(int i = 0; i < words.size(); ++i) {
      if(words[i].size() > maxLen) maxLen = words[i].size();
  }
  if(maxLen > maxWidth) return {};
  vector<string> res;
  int num_words_curr_line = 0;
  int curr_line_length = 0;
  int curr_line_start = 0;
  for(int i = 0; i < words.size(); ++i) {
    ++num_words_curr_line;
    size_t lookahead_line_length = curr_line_length + words[i].size() + (num_words_curr_line - 1);
    if(lookahead_line_length == maxWidth) {
      res.push_back(JoinALineWithSpace(words, curr_line_start, i, i - curr_line_start));
      curr_line_start = i + 1;
      curr_line_length = 0;
      num_words_curr_line = 0;
    } else if(lookahead_line_length > maxWidth) {
      res.push_back(JoinALineWithSpace(words, curr_line_start, i - 1, maxWidth - curr_line_start));
      curr_line_start = i;
      curr_line_length = words[i].size();
      num_words_curr_line = 1;
    } else {
      curr_line_length += words[i].size();
    }
  }
  if(num_words_curr_line > 0) {
    string line = JoinALineWithSpace(words, curr_line_start, words.size() - 1, num_words_curr_line - 1);
    line.append(maxWidth - curr_line_length - (num_words_curr_line - 1), ' ');
    res.push_back(line);
  }
  return res;
}

int main(void) {
  vector<string> words{"This", "is", "an", "example", "of", "text", "justification"};
  vector<string> res = fullJustify(words, 16);
  for(int i = 0; i < res.size(); ++i) cout << res[i] << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值