Number of Lines To Write String

Number of Lines To Write String

You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on.

You are trying to write s across several lines, where each line is no longer than 100 pixels. Starting at the beginning of s, write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s, continue writing as many letters as you can on the second line. Continue this process until you have written all of s.

Return an array result of length 2 where:

  • result[0] is the total number of lines.

  • result[1] is the width of the last line in pixels.

LeetCode Problem - 806

class Solution {
    public int[] numberOfLines(int[] widths, String s) {
        int count = 1; // Initialize the count of lines to 1 (starting from the first line)
        int flag = 0; // This variable keeps track of the current width of the line

        // Iterate through each character in the string 's'
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i); // Get the current character in the string
            int val = widths[ch - 'a']; // Get the width of the character from the 'widths' array

            // Check if adding the current character's width exceeds the limit of 100 units per line
            if (flag + val > 100) {
                count++; // If it exceeds 100, move to a new line
                flag = val; // Set the width of the new line to the width of the current character
            } else {
                flag += val; // If it fits, just add the width of the current character to the current line
            }
        }

        // Return the number of lines and the width used in the last line
        return new int[]{count, flag};
    }
}

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!