text-justification
来源:互联网 发布:威盾软件 编辑:程序博客网 时间:2024/05/29 09:40
题目:
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:
[
“This is an”,
“example of text”,
“justification. ”
]
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.
程序:
class Solution {public: vector<string> fullJustify(vector<string> &words, int L) { int len = words.size(); if (len == 0||L<=0) return words; vector<string> res; string line; int i = 0; while (i < len) { int n = 0;//文字长度 int j = 0;//单词个数 while (n+j-1 <= L&&i<len) { n = n + words[i].size(); i++; j++; } if (n+j-1>L) { i--; j--; n = n - words[i].size(); } if (j == 1 && i < len) { int length = L - n;//只有一个单词的特殊情况 string str(length, ' '); line = words[i - 1] + str; res.push_back(line); line.clear(); continue; } if (i == len)//行尾 { for (int k = j - 1; k >= 0; k--) { if (k) line = line + words[i - (k + 1)] + " "; else line = line + words[i - (k + 1)]; } if(line.size()<L) { string space(L-line.size(),' '); line=line+space; } res.push_back(line); line.clear(); break; } int length = L - n;//空格长度 int ave;//平均空格长度 int left;//多余空格长度 if (length) { ave = length / (j - 1);//平均空格 left = length % (j - 1);//多余出来的空格靠左的每个加一 } string str(ave, ' '); for (int k = j-1; k>=0; k--) { if (k != 0) line = line + words[i-(k+1)] + str; else line = line + words[i-(k+1)]; if (left) { line = line + " "; left--; } } res.push_back(line); line.clear(); } return res; }};
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- 比特率与波特率的区别与联系
- hdu-5924-Mr. Frog’s Problem
- CVTE前端面试
- (三)几种排序算法的学习总结(快速排序)
- Candies SPFA + 栈
- text-justification
- 【ESP32视频分享3】Ubuntu使用 Eclipse开发ESP32程序
- Eclipse控制台log4j日志级不同颜色显示
- 微信小程序学习笔记 2.3.1 视图与渲染
- NPOI之Excel——合并单元格、设置样式、输入公式
- C语言读写mysql
- Servlet工作原理解析
- 99乘法表1
- keks (删数问题)