The number of lines needed to write a string

10. The number of lines required to write a string

10.1. Requirements for the title

​​ We want to write the given string S on each line from left to right, and the maximum width of each line is 100 units. If we write a certain letter, the line will exceed 100 units. Then we should write this letter to the next line. We are given an array widths, this array widths[0] represents the required units of 'a', widths[1] represents the required units of 'b', ..., widths[25] represents the required units of 'z'.

​​ Now answer two questions: how many lines can fit S at least, and what units of width does the last line use? Return your answer as a list of integers of length 2.

示例 1:
输入: 
widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]
S = "abcdefghijklmnopqrstuvwxyz"
输出: [3, 60]
解释: 
所有的字符拥有相同的占用单位10。所以书写所有的26个字母,
我们需要2个整行和占用60个单位的一行。


示例 2:
输入: 
widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]
S = "bbbcccdddaaa"
输出: [2, 4]
解释: 
除去字母'a'所有的字符都是相同的单位10,并且字符串 "bbbcccdddaa" 将会覆盖 9 * 10 + 2 * 4 = 98 个单位.
最后一个字母 'a' 将会被写到第二行,因为第一行只剩下2个单位了。
所以,这个答案是2行,第二行有4个单位宽度。


注:
字符串 S 的长度在 [1, 1000] 的范围。
S 只包含小写字母。
widths 是长度为 26的数组。
widths[i] 值的范围在 [2, 10]。

Source: LeetCode
Link: https://leetcode-cn.com/problems/number-of-lines-to-write-string

10.2. Problem solving ideas

​​ In this question, we only need to know the given string and the corresponding weight of each character in the string, and then calculate and judge.
​​ First create a loop to take out the corresponding weight of each character. Then add the weights. If it is greater than 100, stop adding and reassign the last number to the number for calculating the weight. The final output can be.

Please add image description

10.3. Algorithms

class Solution {
    
    
    public int[] numberOfLines(int[] widths, String s) {
    
    
        //在此题中,我们只需要知道给出的字符串以及字符串中各个字符对应的重量,进行计算与判断即可
        //先创建一个循环,将每个字符相对应的重量取出来。
        //再将重量进行相加,大于100就停止相加并将最后那个数重新赋值给计算重量的数。
        //最后输出即可
        int width = 0;
        int maxWidth = 100;
        int line = 1;
        for (int i = 0; i < s.length(); i++) {
    
    
            //将每个字符取出来并转化成相对应的值
            int need = widths[s.charAt(i) - 'a'];
            //将重量加起来
            width += need;
            //判断是否超出最大重量
            if (width > maxWidth){
    
    
                //将行数计算出来
                line++;
                //给重量重新赋值
                width = need;
            }
        }
        //输出
        return new int[]{
    
    line, width};
    }
}

Guess you like

Origin blog.csdn.net/qq_52916408/article/details/124117497