68. Text Justification
来源:互联网 发布:cfca 网络身份认证平台 编辑:程序博客网 时间:2024/06/05 16:19
解题思路
这是一个典型的分治算法,基本思路就是:扫描字符串数组,累加长度,当发现长度超过最大长度的时候,就把前面的几个字符串按规则组合,加入到List中。
public List<String> fullJustify(String[] words, int maxWidth) { List<String> result = new ArrayList<>(); if(words==null||words.length==0) return result; if(maxWidth==0) { result.add(""); return result; } greedy(words,maxWidth,result); return result; } public void greedy(String[] words,int maxWidth,List<String> result ) { if(words==null||words.length==0) return; int sum = words[0].length(); int i; for (i=1;i<words.length;i++) { sum += (words[i].length()+1); if(sum>maxWidth) break; } if(sum<=maxWidth) { String re = ""; if (words.length==1) { re += words[0]; for (int j=0;j<maxWidth-words[0].length();j++) re += " "; result.add(re); return; } int len = 0; for (int j=0;j<words.length-1;j++) { len += (words[j].length()+1); re += words[j]; re += " "; } re += words[words.length-1]; len += words[words.length-1].length(); for (int j =0;j<maxWidth-len;j++) re += " "; result.add(re); return; } String[] s1 = Arrays.copyOfRange(words,0,i); String[] s2 = Arrays.copyOfRange(words,i,words.length); result.add(mergeString(s1,maxWidth)); greedy(s2,maxWidth,result); } public String mergeString(String[] words,int maxWidth) { String result = ""; int sum = 0; for(int i=0;i<words.length;i++) sum += words[i].length(); if (words.length==1) { result += words[0]; for (int i=0;i<maxWidth-words[0].length();i++) result += " "; return result; } int meanSpace = (maxWidth-sum)/(words.length-1); int moreSpace = (maxWidth-sum)%(words.length-1); for (int i=0;i<words.length-1;i++) { result += words[i]; for (int j=0;j<meanSpace;j++) result += " "; if(moreSpace>0) { result += " "; moreSpace--; } } result += words[words.length-1]; return result; }
0 0
- LeetCode 68. Text Justification
- LeetCode --- 68. Text Justification
- [Leetcode] 68. Text Justification
- [leetcode] 68.Text Justification
- 68. Text Justification
- 68. Text Justification
- [leetcode] 68. Text Justification
- LeetCode 68. Text Justification
- Leetcode 68. Text Justification
- LeetCode 68. Text Justification
- 68. Text Justification
- leetcode 68. Text Justification
- 68. Text Justification
- [LeetCode] 68. Text Justification
- LeetCode-68.Text Justification
- 68. Text Justification
- leetcode 68. Text Justification
- 68. Text Justification
- [Android] SQlite的使用
- 请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
- 后缀自动机 转变为 后缀数组
- Java堆、栈和常量池以及相关String的详细讲解(经典中的经典)深入理解
- HDU 5917 Instability (ramsey定理)
- 68. Text Justification
- 使用itoa函数输出二进制格式
- python decode encode问题
- Linux文件编程之虚拟文件系统(VFS)
- 55. Jump Game
- oracle基础教程(第三天)Java操作数据库
- 【SSM 7】Mybatis底层封装思路
- .NET异步编程总结----四种实现模式
- adb的简单用法