LeetCode 806: Number of Lines To Write String Solution

Master LeetCode problem 806 (Number of Lines To Write String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

806. Number of Lines To Write String

Problem Explanation

Explanation

To solve this problem, we iterate through each character in the input string s. We keep track of the total width written so far and the number of lines used. If adding the width of the current character exceeds 100 pixels, we increment the number of lines and reset the total width to the width of the current character. After iterating through all characters, we return the total number of lines and the width of the last line.

  • Time complexity: O(n) where n is the length of the input string s.
  • Space complexity: O(1)

Solution Code

class Solution {
    public int[] numberOfLines(int[] widths, String s) {
        int lines = 1, width = 0;
        
        for (char c : s.toCharArray()) {
            int charWidth = widths[c - 'a'];
            if (width + charWidth > 100) {
                lines++;
                width = charWidth;
            } else {
                width += charWidth;
            }
        }
        
        return new int[]{lines, width};
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 806 (Number of Lines To Write String)?

This page provides optimized solutions for LeetCode problem 806 (Number of Lines To Write String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 806 (Number of Lines To Write String)?

The time complexity for LeetCode 806 (Number of Lines To Write String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 806 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 806 in Java, C++, or Python.

Back to LeetCode Solutions