chenhuiYj / chenhuiYj/note

练习题11:写字符串需要的行数

Open
#27 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
HTML
Stars
6
Forks
0
PR merge metrics
No merged PRs in 30d

Description

我们要把给定的字符串 S 从左到右写到每一行上,每一行的最大宽度为100个单位,如果我们在写某个字母的时候会使这行超过了100 个单位,那么我们应该把这个字母写到下一行。我们给定了一个数组 widths ,这个数组 widths[0] 代表 'a' 需要的单位, widths[1] 代表 'b' 需要的单位,..., widths[25] 代表 'z' 需要的单位。

现在回答两个问题:至少多少行能放下S,以及最后一行使用的宽度是多少个单位?将你的答案作为长度为2的整数列表返回。

示例 1:
输入: 
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"
输出: [3, 60]
解释: 
所有的字符拥有相同的占用单位10。所以书写所有的26个字母,
我们需要2个整行和占用60个单位的一行。


输入: 
widths = [4,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 = "bbbcccdddaaa"
输出: [2, 4]
解释: 
除去字母'a'所有的字符都是相同的单位10,并且字符串 "bbbcccdddaa" 将会覆盖 9 * 10 + 2 * 4 = 98 个单位.
最后一个字母 'a' 将会被写到第二行,因为第一行只剩下2个单位了。
所以,这个答案是2行,第二行有4个单位宽度。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-lines-to-write-string
著作权归领扣网络所有

解题思路

1.要知道到哪个字母就超过 100 的单位,那么就要知道占有一个字母所占有的单位

2.新增 count=0, row=1。遍历输入的 S ,取到每一个字母占有的单位,当 count 加上当前字母占有的宽度如果大于100,那么row++,count=0;

3.最后返回 [row, count]

var numberOfLines = function(widths, S) {
    let _ws = "abcdefghijklmnopqrstuvwxyz"
    let wordWidth={}
    for(let i=0;i<widths.length;i++){
        wordWidth[_ws[i]]=widths[i]
    }
    let count=0
    let row=1
    for(let i=0;i<S.length;i++){
        if(count+wordWidth[S[i]]>100){
            row++
            count=0
        }
        count+=wordWidth[S[i]]
    }
    return [row,count]
};

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No target file or test is named. Start by inspecting the repository structure to find where this problem note belongs, then review the inline JavaScript solution and its explanation. Done should be defined by an explicit destination and acceptance criteria for adding or revising this note.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.