题目:

Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.

Return the formatted lines as:

  1. [
  2. "This is an",
  3. "example of text",
  4. "justification. "
  5. ]

Note: Each word is guaranteed not to exceed L in length.

click to show corner cases.

Corner Cases:

  • A line other than the last line might contain only one word. What should you do in this case?
    In this case, that line should be left-justified.

代码:

  1. class Solution {
  2. public:
  3. vector<string> fullJustify(vector<string>& words, int maxWidth) {
  4. vector<string> ret;
  5. vector<string> tmp; // words in one line
  6. int width = ; // total width in one line
  7. const char BLANK=' ';
  8. int i=;
  9. while ( i<words.size() )
  10. {
  11. // judge if a word can be added in a line
  12. if ( width+words[i].size() <= maxWidth )
  13. {
  14. if ( width+words[i].size()==maxWidth )
  15. {
  16. tmp.push_back(words[i]);
  17. width = maxWidth;
  18. }
  19. else
  20. {
  21. tmp.push_back(words[i]+string(,BLANK));
  22. width += words[i].size()+;
  23. }
  24. }
  25. // or create a new line & handle the words[i]
  26. else
  27. {
  28. // CREAT A NEW LINE
  29. // number of blank need to add
  30. int blank_num = maxWidth - width;
  31. if ( tmp.back()[tmp.back().size()-]==BLANK )
  32. {
  33. tmp.back() = string(tmp.back().begin(),tmp.back().end()-);
  34. blank_num = blank_num + ;
  35. }
  36. // number of position for blanks
  37. int pos_num = tmp.size()-;
  38. if ( pos_num== )
  39. {
  40. ret.push_back(tmp.back()+string(blank_num, BLANK));
  41. }
  42. else
  43. {
  44. // number of blanks remain to be evenly distributed
  45. int blank_remain = blank_num % pos_num;
  46. for ( int j=; j<tmp.size()-; ++j )
  47. {
  48. tmp[j] = tmp[j]+ string(blank_num/pos_num, BLANK);
  49. }
  50. for ( int j=; j<blank_remain; ++j )
  51. {
  52. tmp[j] = tmp[j] + string(, BLANK);
  53. }
  54. string str = "";
  55. for ( int j=; j<tmp.size(); ++j ) str += tmp[j];
  56. ret.push_back(str);
  57. }
  58. // HANDLE THE words[i]
  59. tmp.clear();
  60. if ( words[i].size()==maxWidth )
  61. {
  62. tmp.push_back(words[i]);
  63. width = maxWidth;
  64. }
  65. else
  66. {
  67. tmp.push_back(words[i]+string(, BLANK));
  68. width = words[i].size()+;
  69. }
  70. }
  71. ++i;
  72. }
  73. // address the remain line
  74. if ( tmp.size()!= )
  75. {
  76. int blank_num = maxWidth - width;
  77. string last_line = "";
  78. for ( int i=; i<tmp.size(); ++i ) last_line += tmp[i];
  79. ret.push_back(last_line+string(blank_num, BLANK));
  80. }
  81. return ret;
  82. }
  83. };

tips:

1. 要对string的各种操作都很熟悉

2. 要理解对题意,重点是到底啥是evenly:意思是不能evenly,就从左边到右一个个分配。

3. 扫一扫各种test case,多扫几遍可以AC了。

这道题自己扫了4次,终于AC了;经验就是,如果不能做到第一次把所有关键细节都考虑完全了,至少把一些细节(诸如blank_num,pos_num,blank_remain)单独列拎出来,这样做的好处就是如果遇上各种需要考虑的corner cases可以单独处理这些关键细节,而不用影响其他的部分。

====================================================

第二次过这道题,算是写过的leetcode中最繁琐的之一了,欣慰的是一次AC了。

  1. class Solution {
  2. public:
  3. vector<string> fullJustify(vector<string>& words, int maxWidth) {
  4. vector<string> ret;
  5. vector<string> tmp;
  6. int currWidth = ;
  7. for ( int i=; i<words.size()-; ++i )
  8. {
  9. // no room for curr word
  10. if ( currWidth+words[i].size()>maxWidth )
  11. {
  12. // address words already in tmp
  13. int blank = maxWidth - currWidth + ;
  14. tmp.back() = tmp.back().substr(,tmp.back().size()-);
  15. if ( tmp.size()> ){
  16. int even = blank/(tmp.size()-);
  17. for ( int k=; k<tmp.size()-; k++ ) tmp[k] = tmp[k] + string(even,' ');
  18. int remain = blank%(tmp.size()-);
  19. for ( int k=; k<remain; k++ ) tmp[k] = tmp[k] + " ";
  20. string str = "";
  21. for ( int k=; k<tmp.size(); ++k ) str += tmp[k];
  22. ret.push_back(str);
  23. }
  24. else{
  25. tmp[] = tmp[]+string(blank,' ');
  26. ret.push_back(tmp[]);
  27. }
  28. tmp.clear();
  29. // consider words[i]'s width
  30. if ( words[i].size()<maxWidth ) {
  31. tmp.push_back(words[i]+" ");
  32. currWidth = words[i].size()+;
  33. }
  34. else{
  35. ret.push_back(words[i]);
  36. currWidth = ;
  37. }
  38. }
  39. // room for current word
  40. else
  41. {
  42. // no room for extra blank
  43. if ( currWidth+words[i].size()==maxWidth )
  44. {
  45. tmp.push_back(words[i]);
  46. string str = "";
  47. for ( int k=; k<tmp.size(); ++k ) str += tmp[k];
  48. ret.push_back(str);
  49. tmp.clear();
  50. currWidth = ;
  51. }
  52. // room for extra blank
  53. else
  54. {
  55. tmp.push_back(words[i]+" ");
  56. currWidth += words[i].size()+;
  57. }
  58. }
  59. }
  60. // last line
  61. if ( currWidth+words[words.size()-].size()>maxWidth )
  62. {
  63. // address words already in tmp
  64. int blank = maxWidth - currWidth + ;
  65. tmp.back() = tmp.back().substr(,tmp.back().size()-);
  66. if ( tmp.size()> ){
  67. int even = blank/(tmp.size()-);
  68. for ( int k=; k<tmp.size()-; k++ ) tmp[k] = tmp[k] + string(even,' ');
  69. int remain = blank%(tmp.size()-);
  70. for ( int k=; k<remain; k++ ) tmp[k] = tmp[k] + " ";
  71. string str = "";
  72. for ( int k=; k<tmp.size(); ++k ) str += tmp[k];
  73. ret.push_back(str);
  74. }
  75. else{
  76. tmp[] = tmp[]+string(blank,' ');
  77. ret.push_back(tmp[]);
  78. }
  79. // address the last line
  80. blank = maxWidth - words[words.size()-].size();
  81. ret.push_back(words[words.size()-]+string(blank,' '));
  82. }
  83. else
  84. {
  85. tmp.push_back(words[words.size()-]+string(maxWidth-currWidth-words[words.size()-].size(),' '));
  86. string str = "";
  87. for ( int k=; k<tmp.size(); ++k ) str += tmp[k];
  88. ret.push_back(str);
  89. }
  90. return ret;
  91. }
  92. };

【Text Justification】cpp的更多相关文章

  1. hdu 4739【位运算】.cpp

    题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...

  2. Hdu 4734 【数位DP】.cpp

    题意: 我们定义十进制数x的权值为f(x) = a(n)*2^(n-1)+a(n-1)*2(n-2)+...a(2)*2+a(1)*1,a(i)表示十进制数x中第i位的数字. 题目给出a,b,求出0~ ...

  3. 【ZigZag Conversion】cpp

    题目: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows l ...

  4. 【Valid Sudoku】cpp

    题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...

  5. 【Permutations II】cpp

    题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...

  6. 【Subsets II】cpp

    题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. ...

  7. 【Sort Colors】cpp

    题目: Given an array with n objects colored red, white or blue, sort them so that objects of the same ...

  8. 【Sort List】cpp

    题目: Sort a linked list in O(n log n) time using constant space complexity. 代码: /** * Definition for ...

  9. 【Path Sum】cpp

    题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...

随机推荐

  1. ffmpeg 安装和参数介绍

    0.说明: 1).configure,这一步一般用来生成 Makefile,为下一步的编译做准备,你可以通过在 configure 后加上参数来对安装进行控制,比如代码:./configure –pr ...

  2. 使用Excel消费C4C的OData service

    步骤比较简单, 打开Excel的标签Data->From Other Sources->From OData Data Feed: 输入如下url: https://.c4c.saphyb ...

  3. JavaRebel 2.0 发布,一个JVM插件

    JavaRebel是一个JVM插件(-javaagent),能够即时重载java class更改,因此不需要重新部署一个应用或者重启容器,节约开发者时间. JavaRebel 2.0的新特征: 改变了 ...

  4. 模仿ArcGIS用Graphics重绘的直方图分级调节器

    using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using Sy ...

  5. 20145238-荆玉茗 《Java程序设计》第四次实验报告

    20145238<Java程序设计>第四次实验报告 实验四 Android环境搭建 实验内容 1.搭建Android环境 2.运行Android 3.修改代码,能输出学号 实验步骤 搭建A ...

  6. Oracle字符编码与汉字存储长度的处理

    执行如下语句,查看汉字在数据库中所占的字节: select vsize('汉') from dual; 一般情况下,得到的结果大部分为值:2 或 3 一般linux下安装oracle数据库,默认字符编 ...

  7. python中的zipfile

    zipfile - Work with ZIP archives ZipFile.namelist() Return a list of archive members by name. 返回压缩成员 ...

  8. 关于var和ES6中的let,const的理解

    var的作用就不多说了,下面说说var的缺点: 1.var可以重复声明 var a = 1; var a = 5; console.log(a); //5 不会报错 在像这些这些严谨的语言来说,一般是 ...

  9. http2.2配置

    http: 超文本传输协议,工作在应用层 CentOS 6程序环境:httpd-2.2 配置文件: /etc/httpd/conf/httpd.conf /etc/httpd/conf.d/*.con ...

  10. ethereum(以太坊)(十二)--应用(二)__投票(基础总和)

    编写应用合约之前,先弄清它的逻辑,有助于我们更好的部署合约 pragma solidity ^0.4.21; pragma experimental ABIEncoderV2; contract vo ...