Number of Lines To Write String

You are given a string s of lowercase English letters and an array width 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:

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

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

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]

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

vector<intnumberOfLines(vector<int&widthsstring s)
{
    vector<int> res;
    map<charint> mp;
    for (int i = 0; i < widths.size(); i++)
        mp[i + 'a'] = widths[i];
    int i = 0;
    int n = s.size();
    int num = 0;
    while (i < n)
    {
        int cnt = 0;
        while (cnt < 100 && i < n)
        {
            if (cnt + mp[s[i]] > 100)
                break;
            else
                cnt += mp[s[i]];
            i++;
        }
        num++;
        if (i == n)
        {
            res.push_back(num);
            res.push_back(cnt);
        }
    }
    return res;
}

int main()
{
    vector<int> widths = {10101010101010101010,
                          10101010101010101010,
                          101010101010};
    string s = "abcdefghijklmnopqrstuvwxyz";

    vector<int> res = numberOfLines(widths, s);

    for (int i = 0; i < res.size(); i++)
    {
        cout << res[i] << " ";
    }
    return 0;
}


No comments:

Post a Comment