Number of Lines To Write String

easy strings simulation

Problem

Given an array widths of 26 integers (width of 'a'..'z') and a string s, write s across as few lines as possible where each line is at most 100 units wide. Return [number_of_lines, width_of_last_line].

Inputwidths = [10]*26, s = "abcdefghijklmnopqrstuvwxyz"
Output[3, 60]
26 letters * 10 = 260 units = 3 lines (100, 100, 60).

def numberOfLines(widths, s):
    lines, cur = 1, 0
    for c in s:
        w = widths[ord(c) - ord('a')]
        if cur + w > 100:
            lines += 1
            cur = w
        else:
            cur += w
    return [lines, cur]
var numberOfLines = function(widths, s) {
    let lines = 1, cur = 0;
    for (const c of s) {
        const w = widths[c.charCodeAt(0) - 97];
        if (cur + w > 100) { lines++; cur = w; }
        else cur += w;
    }
    return [lines, cur];
};
class Solution {
    public int[] numberOfLines(int[] widths, String s) {
        int lines = 1, cur = 0;
        for (char c : s.toCharArray()) {
            int w = widths[c - 'a'];
            if (cur + w > 100) { lines++; cur = w; }
            else cur += w;
        }
        return new int[]{lines, cur};
    }
}
class Solution {
public:
    vector<int> numberOfLines(vector<int>& widths, string s) {
        int lines = 1, cur = 0;
        for (char c : s) {
            int w = widths[c - 'a'];
            if (cur + w > 100) { lines++; cur = w; }
            else cur += w;
        }
        return {lines, cur};
    }
};
Time: O(n) Space: O(1)