806. Number of Lines To Write String

We are to write the letters of a given string S, from left to right into lines. Each line has maximum width 100 units, and if writing a letter would cause the width of the line to exceed 100 units, it is 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[25] is the width of ‘z’.
Now answer two questions: how many lines have at least one character from S, and what is the width used by the last such line? Return your answer as an integer list of length 2.
这里写图片描述
这里写图片描述


题解:

package com.leetcode;

public class WritingString {

    public static void main(String[] args) {
        int[] 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 };
        String S = "bbbcccdddaaa";
        int[] ans = numberOfLines(widths, S);
        System.out.println(ans[0] + ", " + ans[1]);
    }

    public static int[] numberOfLines(int[] widths, String S) {
        if (S.isEmpty())
            return new int[] { 0, 0 };

        int lines = 1;
        int curr_widths = 0;
        for (int i = 0; i < S.length(); i++) {
            curr_widths += widths[S.charAt(i) - 'a'];
            if (curr_widths > 100) {
                lines++;
                curr_widths = 0;
                i--;
            }
        }
        return new int[] { lines, curr_widths };
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值