806. Number of Lines to Write String

Source: Internet
Author: User

We is to write the letters of a given string S, from left to right into lines. Each line have maximum width units, and if writing a letter would cause the width of the "line" exceed units, it I s written on the next line. We are given an array widths, an array where widths[0] is the width of ' a ', widths[1] is the width of ' B ', ..., and widths [+] is the width of ' z '.

Now answer, Questions:how many lines has at least one character from S, and what's the width used by the last such L Ine? Return your answer as an integer list of length 2.

Example:
Input:
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"
Output: [3, 60]
Explanation:
All letters has the same length of 10. To write all letters,
We need-lines and one line with the units.

Example:
Input:
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"
Output: [2, 4]
Explanation:
All letters except ' a ' has the same length of ten, and
"Bbbcccdddaa" would cover 9 * + 2 * 4 = 98 units.
For the last ' a ', it's written on the second line because
There is a 2 units left on the first line.
The answer is 2 lines, plus 4 units on the second line.

Note:

    • The length of S'll is in the range [1, 1000].
    • S would only contain lowercase letters.
    • Widths is an array of length 26.
    • Widths[i] would be in the range of [2, 10].
class Solution:    def numberOfLines(self, widths, S):        """        :type widths: List[int]        :type S: str        :rtype: List[int]        """        line,pos = 1,0        for i in S:            wid = widths[ord(i)-ord(‘a‘)]            pos += wid            if pos>100:                pos = wid                line += 1        return [line,pos]

806. Number of Lines to Write String

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.