DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Number of Lines To Write String

var numberOfLines = function (widths, s) {
  let dummyAlphabet = "abcdefghijklmnopqrstuvwxyz";
  let map = new Map();
  let maxCountInLine = 100;
  let rows = 0;

  for (let i = 0; i < dummyAlphabet.length; i++) {
    map.set(dummyAlphabet[i], widths[i]);
  }

  for (let i = 0; i < s.length; i++) {
    let char = s[i];
    let width = map.get(char);
    maxCountInLine = maxCountInLine - width;
    if (maxCountInLine === 0) {
      rows++;
      maxCountInLine = 100;
    } else if (maxCountInLine < 0) {
      rows++;
      maxCountInLine = 100;
      maxCountInLine = maxCountInLine - width;
    }
  }
  let nextLineUsed = 100 - maxCountInLine;
  let fRows = nextLineUsed > 0 ? rows + 1 : rows;
  return [fRows, nextLineUsed === 0 ? 100 : nextLineUsed];
};


Enter fullscreen mode Exit fullscreen mode

Top comments (0)