Leetcode -- Text Justification
来源:互联网 发布:xp禁止安装软件 编辑:程序博客网 时间:2024/06/16 10:44
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 exactlyL 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.
分析:
细节实现题,没有太多算法。
class Solution {public: string process(vector<string> words,int a,int b,int len) { int sz=words[a].size(); for(int i=a+1;i<=b;++i) sz+=1+words[i].size(); int left = len-sz; string res=words[a]; if(b>a) { int sep = left/(b-a); int fir = left-sep*(b-a); for(int i=a+1;i<=b;++i) { if(i-a-1<fir) res+=" "; res+=string(sep+1,' '); res+=words[i]; } } else res+=string(left,' '); return res; } vector<string> fullJustify(vector<string>& words, int maxWidth) { int last=0; vector<string> res; int n=words.size(); if(n==0) return res; int cnt=0; for(int i=0;i<n;++i) { cnt += words[i].size(); if(i!=last) cnt++; if(cnt==maxWidth) { res.push_back(process(words,last,i,maxWidth)); last=i+1; cnt = 0; } else if(cnt>maxWidth) { res.push_back(process(words,last,i-1,maxWidth)); last=i; cnt = words[i].size(); } } if(cnt>0||res.empty()) { string tmp=words[last]; for (int i=last+1;i<n;++i) tmp+=" "+words[i]; tmp+=string(maxWidth-cnt,' '); res.push_back(tmp); } return res; }};
- LeetCode : Text Justification
- [LeetCode] Text Justification
- leetcode 103: Text Justification
- [LeetCode]Text Justification
- [leetcode] Text Justification
- Text Justification leetcode
- Leetcode: Text Justification
- leetcode Text Justification
- LeetCode Text Justification
- LeetCode | Text Justification
- LeetCode Text Justification
- [Leetcode] Text Justification (Java)
- LeetCode OJ:Text Justification
- Leetcode: Text Justification
- [LeetCode] Text Justification
- 【LeetCode】Text Justification
- Text Justification -- LeetCode
- LeetCode: Text Justification [068]
- Android随机生成颜色值
- 拦截软键盘的返回键 Intercept back button from soft keyboard
- 软件测试常见风险分析
- Java IO: 网络
- 真正的宝塔线指标
- Leetcode -- Text Justification
- NDK在studio中的编译
- 如何学好算法
- android listview 嵌套ListView,子lv高度的问题
- 关于.net平台开发程序连接oracle数据库查询语句中包含汉字的问题
- Android自定义ListView
- Android adb.exe程序启动不起来,如何处理
- 【工具】字符串 加密 解密 不可逆加密 拆分 合并
- 【BZOJ4305】数列的GCD