806. Number of Lines To Write String
整体思路:
- 先得到一个res = {a : 80 , b : 10, c : 20.....的key-value对象}(目的是当调用res["a"]时得到一个等于10的值);
- 遍历传入的字符串,把每个元素带入到res中,并把所有的值进行累加;得到一个累加值sum,如:sum= sum + res["a"] + res["b"] + res["c"]....+res["z"];
- 当sum>100时,例如res["a"] + res["b"] + res["c"] =110,大于100,此时第一行应该只有res["a"]和res["b"],将flag加1,同时给sum赋值为当前的res[S[i]]值,sum重新开始下一行计数;
1 var numberOfLines = function (widths, S) { 2 let letterArr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; 3 let res = {}; 4 let sum = 0; 5 // flag要从1开始计数,不满一行按一行计算 6 let flag = 1; 7 8 letterArr.forEach((item, index) => { 9 //item 表示letterArr中的每个元素 10 //index 表示letterArr中的每个元素的索引值 11 // 得到一个对象{ a: 10,......} 12 res[item] = widths[index]; 13 }); 14 // 遍历传入的字符串,拿到每一个字母 15 for (let i = 0; i < S.length; i++) { 16 sum = sum + res[S[i]]; 17 //当累加的和大于100时,也就是超出一行 18 if (sum > 100) { 19 flag++; 20 //给sum赋值为当前的res[S[i]],sum重新开始下一行计数 21 sum = res[S[i]]; 22 } else if (sum == 100) { 23 flag++; 24 sum = 0; 25 } 26 } 27 return [flag, sum]; 28 29 }; 30 31 32 var widths = [10, 10, 10, 10, 13, 13, 13, 10, 7, 8, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10] 33 var S = "abcdefghijklmnopqrstuvwxyz"; 34 console.log(numberOfLines(widths, S));