​LeetCode刷題實戰68:文本左右對齊

2021-03-06 程序IT圈

算法的重要性,我就不多說了吧,想去大廠,就必須要經過基礎知識和業務邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !

今天和大家聊的問題叫做 文本左右對齊,我們先來看題面:

https://leetcode-cn.com/problems/minimum-path-sum/

Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth 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 maxWidth 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.

題意給定一個單詞數組和一個長度 maxWidth,重新排版單詞,使其成為每行恰好有 maxWidth 個字符,且左右兩端對齊的文本。你應該使用「貪心算法」來放置給定的單詞;也就是說,儘可能多地往每行中放置單詞。必要時可用空格 ' ' 填充,使得每行恰好有 maxWidth 個字符。要求儘可能均勻分配單詞間的空格數量。如果某一行單詞間的空格不能均勻分配,則左側放置的空格數要多於右側的空格數。文本的最後一行應為左對齊,且單詞之間不插入額外的空格。每個單詞的長度大於 0,小於等於 maxWidth。

輸入:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
輸出:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]

解題https://blog.csdn.net/qq_41231926/article/details/82847865思路:依次遍歷數組中的每一個元素,每一層放儘可能多的字符本題沒有應用到什麼算法方面的知識,根據題意寫就行了,算是LeetCode中困難難度的簡單題。需要注意以下幾個注意點:(2)如果一行中只有一個單詞,其後需要填充空格至maxWidth長度。(3)如果一行中有多個單詞,其單詞之間空格的計算可以先算平均分配每兩個單詞之間能分配到的空格數averageSpace,再將多餘的空格數remainSpace從左到右依次填充進兩個單詞的間隔裡。整個實現過程我們只遍歷了數組words一次,因此時間複雜度是O(n)級別的,其中n為words數組的長度。空間複雜度是O(1)。


public class Solution {
 
  public List<String> fullJustify(String[] words, int maxWidth) {
    List<String> list = new ArrayList<>();
    int n = words.length;
    if(n == 0) {
      return list;
    }
    //index represents which position in array words we are traversing now
    int index = 0;
    while(index < n) {
      //every String in list contains 1 word or more
      int len = words[index].length();
      int i = index + 1;
      for (; i < words.length; i++) {
        if(len + words[i].length() + 1 > maxWidth) {
          break;
        }
        len += words[i].length() + 1;
      }
      //levelLen represents how many characters that isn't space in erery String
      int levelLen = 0;
      for (int j = index; j < i; j++) {
        levelLen += words[j].length();
      }
      //numSpace represents how many space between 2 words
      int numSpace = i - index - 1;
      //string represents every String
      String string = "";
      if(i != words.length) {
        //if we haven't traversed all the words
        if(numSpace != 0) {
          //if this String has more than one word
          int[] spaces = new int[numSpace];
          int averageSpace = (maxWidth - levelLen) / numSpace;
          int remainSpace = maxWidth - levelLen - numSpace * averageSpace;
          for (int j = 0; j < numSpace; j++) {
            if(j + 1 <= remainSpace) {
              spaces[j] = 1 + averageSpace;
            }else {
              spaces[j] = averageSpace;
            }
          }
          for (int j = index, k = 0; j < i && k < numSpace;) {
            string += words[j];
            j++;
            for (int num = 0; num < spaces[k]; num++) {
              string += " ";
            }
            k++;
          }
        }
        string += words[i - 1];
        if(numSpace == 0) {
          //if this String only has one word, fill space in the remain position
          while(string.length() < maxWidth) {
            string += " ";
          }
        }
      }else {
        //if we have traversed all the words, the last String we need to put all words on the left
        for (int j = index; j < i - 1; j++) {
          string += words[j] + " ";
        }
        string += words[i - 1];
        while(string.length() < maxWidth) {
          string += " ";
        }
      }
      list.add(string);
      index = i;
    }
    return list;
  }
}

好了,今天的文章就到這裡,如果覺得有所收穫,請順手點個在看或者轉發吧,你們的支持是我最大的動力。

相關焦點

  • LeetCode-68.文本左右對齊(Text Justification)
    68.
  • ​LeetCode刷題實戰139:單詞拆分
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 單詞拆分,我們先來看題面:https://leetcode-cn.com/problems/word-break/Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be
  • 帶你狂刷算法Leetcode題!短時間內快速獲得實戰能力!
    但對於初學者來說,很容易沉迷在刷題的數量中,覺得如果能刷完這1000道題,自己一定能夠有所飛躍。但實際上,低效率的重複對你來說,根本就無法掌握到解題的精髓,一旦題目有所變動,就無法舉一反三。那究竟應該怎麼刷題才高效呢?
  • ​LeetCode刷題實戰79:單詞搜索
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 單詞搜索,我們先來看題面:https://leetcode-cn.com/problems/word-search/Given a 2D board and a word, find if the word exists in the grid.
  • leetcode刷題最強指南(版本1.0)
    為什麼會有這篇刷題指南很多剛開始刷題的同學都有一個困惑:面對leetcode上近兩千道題目,從何刷起
  • ​LeetCode刷題實戰36: 有效的數獨
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 有效的數獨,我們先來看題面:https://leetcode-cn.com/problems/valid-sudoku/Determine if a 9x9 Sudoku board is valid.
  • ​LeetCode刷題實戰198:打家劫舍
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 打家劫舍,我們先來看題面:https://leetcode-cn.com/problems/house-robber/You are a professional robber planning to rob houses along a street.
  • ​LeetCode刷題實戰42:接雨水
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 接雨水,我們先來看題面:https://leetcode-cn.com/problems/trapping-rain-water/Given n non-negative integers representing an elevation map where the width of each bar
  • ​LeetCode刷題實戰57:插入區間
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 插入區間,我們先來看題面:https://leetcode-cn.com/problems/insert-interval/Given a set of non-overlapping intervals, insert a new interval into the intervals (merge
  • ​LeetCode刷題實戰85: 最大矩形
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 最大矩形,我們先來看題面:https://leetcode-cn.com/problems/maximal-rectangle/Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing
  • ​LeetCode刷題實戰148:排序鍊表
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 排序鍊表,我們先來看題面:https://leetcode-cn.com/problems/sort-list/Given the head of a linked list, return the list after sorting it in ascending order.
  • ​LeetCode刷題實戰179:最大數
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 最大數  ,我們先來看題面:https://leetcode-cn.com/problems/largest-number/Given a list of non-negative integers nums, arrange them such that they form the largest number.
  • ​LeetCode刷題實戰70:爬樓梯
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 爬樓梯,我們先來看題面:https://leetcode-cn.com/problems/climbing-stairs/You are climbing a stair case.
  • ​LeetCode刷題實戰134:加油站
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !https://leetcode-cn.com/problems/gas-station/There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
  • 春節大禮包|刷題技巧+80道Leetcode
    為了跳槽,我前兩年的春節都是在刷題中度過的,目前為止刷了小四百道leetcode,也算是有一些經驗,今天就跟大家分享下學習方法和我總結的乾貨。後來發現了 Leetbook[1] 這個寶藏,才算是找到了適合自己的刷題方法。
  • ​LeetCode刷題實戰133:克隆圖
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !https://leetcode-cn.com/problems/clone-graph/Given a reference of a node in a connected undirected graph.
  • ​LeetCode刷題實戰39:組合總和
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 組合總和,我們先來看題面:https://leetcode-cn.com/problems/combination-sumGiven a set of candidate numbers (candidates) (without duplicates) and a target number (target
  • ​LeetCode刷題實戰54:螺旋矩陣
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 螺旋矩陣,我們先來看題面:https://leetcode-cn.com/problems/spiral-matrix/Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in
  • ​LeetCode刷題實戰72:編輯距離
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 編輯距離,我們先來看題面:https://leetcode-cn.com/problems/edit-distanceGiven two words word1 and word2, find the minimum number of operations required to convert word1
  • ​LeetCode刷題實戰119: 楊輝三角 II
    所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 楊輝三角 II,我們先來看題面:https://leetcode-cn.com/problems/pascals-triangle-ii/Given an integer rowIndex, return the rowIndexth row of the Pascal's triangle.