zoukankan      html  css  js  c++  java
  • 806. Number of Lines To Write String

    806. Number of Lines To Write String

    整体思路:
    1. 先得到一个res = {a : 80 , b : 10, c : 20.....的key-value对象}(目的是当调用res["a"]时得到一个等于10的值);
    2. 遍历传入的字符串,把每个元素带入到res中,并把所有的值进行累加;得到一个累加值sum,如:sum= sum + res["a"] + res["b"] + res["c"]....+res["z"];
    3. 当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));
  • 相关阅读:
    CSS3很强大
    Notepad++关闭时自动保留,不弹出提示保存对话框
    数据库中更新或插入表记录
    手动指定网卡优先顺序方法
    在Excel中转换时间戳(timeStamp)
    format z: /p:3 & cipher /w z:abc
    修改eclipse中M2_REPO变量值
    Windows 10 主题的图片位置
    MySQL中 delete from 时提示 1064 错误。
    left join 中 on 与 where 理解
  • 原文地址:https://www.cnblogs.com/MisterZZL/p/10693979.html
Copyright © 2011-2022 走看看