当前位置:   article > 正文

Java | Leetcode Java题解之第68题文本左右对齐

Java | Leetcode Java题解之第68题文本左右对齐

题目:

题解:

  1. class Solution {
  2. private String line(List<String> list,int maxWidth,int totalLength,boolean isLast){
  3. StringBuilder sb = new StringBuilder();
  4. sb.append(list.get(0));
  5. if(list.size() == 1){
  6. String ap = " ".repeat(maxWidth - totalLength);
  7. sb.append(ap);
  8. return sb.toString();
  9. }else{
  10. if(!isLast){
  11. int singleSpace = (maxWidth - totalLength) / (list.size() - 1);
  12. boolean isExact = false;
  13. int ret = 0;
  14. if(singleSpace * (list.size() - 1) == (maxWidth - totalLength)) isExact = true;
  15. else ret = (maxWidth - totalLength) - singleSpace * (list.size() - 1);
  16. String sp = " ".repeat(singleSpace);
  17. for(int i = 1;i < list.size();i++){
  18. // space
  19. if(!isExact && (ret--) > 0) sb.append(" ");
  20. sb.append(sp);
  21. // word
  22. sb.append(list.get(i));
  23. }
  24. return sb.toString();
  25. }else{
  26. for(int i = 1;i < list.size();i++){
  27. // space
  28. sb.append(" ");
  29. // word
  30. sb.append(list.get(i));
  31. }
  32. sb.append(" ".repeat(maxWidth - sb.length()));
  33. return sb.toString();
  34. }
  35. }
  36. }
  37. public List<String> fullJustify(String[] words, int maxWidth) {
  38. int pointer = 0;
  39. int n = words.length;
  40. int totalLength = 0;
  41. int totalSize = 0;
  42. List<String> ans = new ArrayList();
  43. List<String> tmp = new ArrayList();
  44. while(pointer < n){
  45. totalLength += words[pointer].length();
  46. totalSize++;
  47. tmp.add(words[pointer]);
  48. if(totalLength + totalSize - 1 > maxWidth){
  49. tmp.remove(tmp.size() - 1);
  50. ans.add(line(tmp,maxWidth,totalLength - words[pointer].length(),false));
  51. totalLength = words[pointer].length();
  52. totalSize = 1;
  53. tmp.clear();
  54. tmp.add(words[pointer]);
  55. }
  56. pointer++;
  57. }
  58. ans.add(line(tmp,maxWidth,totalLength,true));
  59. return ans;
  60. }
  61. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/556931
推荐阅读
相关标签
  

闽ICP备14008679号